r - 在具有非动态 URL 的多级网站上进行 R 网络抓取
问题描述
如果我没有找到关于这个问题的先前主题,我深表歉意。我想抓取这个网站 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()
}
任何想法?
解决方案
您可以从顶级页面获取所有子页面:
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, .)
现在您可以遍历这些页面并提取您想要的内容
推荐阅读
- node.js - 在 Atom 编辑器中安装 Eslint 时收到警告
- python - 要求确认后如何将数据发送到表单中查看?
- reactjs - ReactJs:`npm run build` 失败,退出状态为 1
- python - 如何使 glob.glob() 深度优先?
- php - 如何进行自定义电子邮件验证(Laravel 5.8)?
- sql - 如何从sql数据库中备份一行?
- jpa - persistence.xml 文件和 hibernate.conf.xml 文件有什么不同,在什么场景下我们应该哪个文件
- swift - 我对 AppDelegate 中的变量有疑问
- python - 无法通过 PyCharm 上的终端运行文件完美运行
- python-3.x - 如何将 .ckpt 转换为 .pb?