Solution 1 :

In order to extract all url, I recommend using the css selector “.field-item li a” and subset according to a pattern.

links <- read_html(url) %>% 
    html_nodes(".field-item li a") %>% 
    html_attr("href") %>% 
    str_subset("fuel-prices/crude")

Solution 2 :

Your XPath needs to be fixed. You can use the following one :

//strong[contains(.,"Oil")]/following-sibling::ul//a

Problem :

I am trying to read off the urls to data from StatsCan as follows:


# 2015
url <- "https://www.nrcan.gc.ca/our-natural-resources/energy-sources-distribution/clean-fossil-fuels/crude-oil/oil-pricing/crude-oil-prices-2015/18122"

x1 <- read_html(url) %>% 
  html_nodes(xpath = '//*[@class="col-md-4"]/ul/li/ul/li/a') %>% 
  html_attr("href")


# 2014
url2 <- "https://www.nrcan.gc.ca/our-natural-resources/energy-sources-distribution/clean-fossil-fuels/crude-oil/oil-pricing/crude-oil-prices-2014/16993"

x2 <- read_html(url) %>% 
  html_nodes(xpath = '//*[@class="col-md-4"]/ul/li/ul/li/a') %>% 
  html_attr("href")

Doing so returns two empty lists; I am confused as this worked for this link: https://www.nrcan.gc.ca/our-natural-resources/energy-sources-distribution/clean-fossil-fuels/crude-oil/oil-pricing/18087. Ultimately I want to loop over the list and read off the tables on each page as so:

for (i in 1:length(x2)){
  out.data <- read_html(x2[i]) %>% 
    html_table(fill = TRUE) %>% 
    `[[`(1) %>% 
    as_tibble()
  write.xlsx(out.data, str_c(destination,i,".xlsx"))
}

By