loop through all pages and scrape data for (i in 1:numberpages) { construct the URL for…
- User
loop through all pages and scrape data
for (i in 1:number_pages) {
construct the URL for the current page
url <- paste0(base_url, "&page=", i)
print loop counter with \r character to overwrite previous print
cat(paste0("Extracting EudraCT codes from page ", i, "/", number_pages), "\r")
read in the HTML content of the page
page <- read_html(url)
use the xpath function to extract the elements
checkbox_element <- page %>% html_nodes(xpath = '//*[@name="enchx"]')
extract the eudract codes ftrom element
eudract_page_codes <- checkbox_element %>% html_attr("value")
append the eudract codes to the vector
eudract_codes <- c(eudract_codes, eudract_page_codes)
select the td element containing the links
td_element <- page %>% html_node("td[colspan='3']")
select all the links within the td element
links <- td_element %>% html_nodes("a")
extract the URLs from the links
urls <- links %>% html_attr("href")
extract the HTML element containing the links
protocol_elements <- page %>% html_nodes(xpath = '//span[contains(text(), "Trial protocol:")]/following-sibling::a')
extract the URLs from the elements
protocol_page_urls <- protocol_elements %>% html_attr("href")
append the urls to the vector
protocol_urls <- c(protocol_urls, protocol_page_urls)
}
Can i wrap this loop in a withProgress() function? Can it update for each loop showing something like "Extracting EudraCT codes from page 3/25". The number of page is "i" (eg 3) and "number_pages" is the total number of pages or loops (eg 25)
- Assistant
Yes, you can wrap this loop in a
withProgress()function to display the progress of the loop. You can update the progress for each iteration of the loop with a message like "Extracting EudraCT codes from page 3/25".To achieve this, you will need to use the
shinypackage in R, which provides thewithProgress()function.Here's a modification of your code using
withProgress():# Load the shiny package library(shiny) # Wrap the loop in the withProgress() function withProgress(message = "Initializing...", value = 0, { for (i in 1:number_pages) { # Update the progress message and the value of the progress bar setProgress(message = paste0("Extracting EudraCT codes from page ", i, "/", number_pages), value = i/number_pages) # (Your original code goes here) } })This will display a progress bar with the current progress and the message "Extracting EudraCT codes from page 3/25". Note that this progress indicator will only be visible if you are using this code within a Shiny app. If you are not using Shiny, you may want to consider other R packages for creating progress bars, such as
txtProgressBar,dplyr::progress_estimated, or .