关于使用rvest和Purrr抓取具有嵌套链接的多个页面的问题 [英] Question about using rvest and purrr for scraping multiple pages with nested links
本文介绍了关于使用rvest和Purrr抓取具有嵌套链接的多个页面的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了下面的代码来摘录FLOTUS在这个link上的所有演讲。代码如下:
library(rvest)
library(purrr)
url_base <- "https://www.presidency.ucsb.edu/documents/presidential-documents-archive-guidebook/remarks-and-statements-the-first-lady-laura-bush?page=%d"
map_df(1:17, function(i) {
# simple but effective progress indicator
cat(".")
pg <- read_html(sprintf(url_base, i))
data.frame(name=html_text(html_nodes(pg, ".views-field-title-1.nowrap")),
title=html_text(html_nodes(pg, "td.views-field-title")),
year=html_text(html_nodes(pg, ".date-display-single")),
stringsAsFactors=FALSE)
}) -> flotus
我还想使用此代码来提取相应演讲的文本。有人知道如何使用我已经编写的代码做到这一点吗?如果是,那会是什么样子?
推荐答案
需要使用html_attr()
函数从表的标题列中检索‘href’属性链接。
library(rvest)
library(purrr)
url_base <- "https://www.presidency.ucsb.edu/documents/presidential-documents-archive-guidebook/remarks-and-statements-the-first-lady-laura-bush?page="
flotus <-map_df(1:16, function(i) {
# simple but effective progress indicator
cat(".")
pg <- read_html(paste0(url_base, i))
#parse the table
df <- html_node(pg, "table") %>% html_table()
#obtain the href from the table's Title column
df$links <-html_nodes(pg, "td.views-field-title") %>%
html_node("a") %>% html_attr("href")
df
})
上面的代码会将语音链接作为数据框中的附加列添加。
第二部分 要提取演讲文本,请检索链接列表,然后循环浏览列表,打开页面,提取所需信息,存储并重复。
#limited the number of pages request for debugging
map_df(flotus$links[1:3], function(link){
print(link)
#Read page
page <- read_html(link)
#extract the content and other info
content <- page %>% html_node("div.field-docs-content") %>% html_text() %>% trimws()
person <- page %>% html_node("div.field-docs-person") %>% html_text() %>% trimws()
citation <- page %>% html_node("div.field-prez-document-citation") %>% html_text() %>% trimws()
#add it to a data struture
data.frame(content, person, citation)
Sys.sleep(1) #Be polite - add a pause to prevent the appearance of attacking the server
})
在这里,所有数据都存储在一个数据帧中。然后,根据将来的意图,可以将此数据帧与上面的数据帧连接起来。
这篇关于关于使用rvest和Purrr抓取具有嵌套链接的多个页面的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文