【问题标题】:R web-scraping on a multiple-level website with non dynamic URLs在具有非动态 URL 的多级网站上进行 R 网络抓取
【发布时间】:2019-04-08 08:38:48
【问题描述】:

如果我没有找到有关此问题的先前主题,我深表歉意。 我想抓取这个网站 http://www.fao.org/countryprofiles/en/ 特别是,此页面包含许多指向国家/地区信息的链接。这些链接的结构是:

http://www.fao.org/countryprofiles/index/en/?iso3=KAZ

http://www.fao.org/countryprofiles/index/en/?iso3=AFG

并且此页面的任何内容都包含我感兴趣的新闻部分。 当然,我可以逐页抓取,但那会浪费时间。

我尝试了以下方法,但不起作用:

countries <- read_html("http://www.fao.org/countryprofiles/en/") %>%
  html_nodes(".linkcountry") %>%
  html_text()

country_news <- list()
sub <- html_session("http://www.fao.org/countryprofiles/en/")

for(i in countries[1:100]){
  page <- sub %>% 
    follow_link(i)  %>% 
    read_html()
  country_news[[i]] <- page %>%
    html_nodes(".white-box") %>%
    html_text()
}

有什么想法吗?

【问题讨论】:

  • 我不太清楚您所说的“逐页”浪费时间是什么意思。除非有 API,否则您将不得不逐页执行(也许您的意思是手动还是自动?)
  • 抱歉,我的意思是手动。当然,我必须逐页进行。

标签: r web-scraping


【解决方案1】:

您可以从顶级页面获取所有子页面:

stem = 'http://www.fao.org'

top_level = paste0(stem, '/countryprofiles/en/')

all_children = read_html(top_level) %>% 
  # ? and = are required to skip /iso3list/en/
  html_nodes(xpath = '//a[contains(@href, "?iso3=")]/@href') %>% 
  html_text %>% paste0(stem, .)

head(all_children)
# [1] "http://www.fao.org/countryprofiles/index/en/?iso3=AFG"
# [2] "http://www.fao.org/countryprofiles/index/en/?iso3=ALB"
# [3] "http://www.fao.org/countryprofiles/index/en/?iso3=DZA"
# [4] "http://www.fao.org/countryprofiles/index/en/?iso3=AND"
# [5] "http://www.fao.org/countryprofiles/index/en/?iso3=AGO"
# [6] "http://www.fao.org/countryprofiles/index/en/?iso3=ATG"

如果您对xpath 不满意,CSS 版本应为:

html_nodes('a') %>% html_attr('href') %>% 
  grep("?iso3=", ., value = TRUE, fixed = TRUE) %>% paste0(stem, .)

现在您可以遍历这些页面并提取您想要的内容

【讨论】:

  • 它正在工作,谢谢。我正在尝试找到一个短循环来正确执行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 2014-05-08
  • 2017-12-30
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多