如果我没有找到关于这个问题的以前的话题,我很抱歉。我特别想刮掉这个网站的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()
}有什么想法吗?
发布于 2019-04-08 17:16:40
您可以从顶级页面中获取所有子页面:
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, .)现在您可以遍历这些页面并提取您想要的内容
https://stackoverflow.com/questions/55569310
复制相似问题