关于使用 rvest 和 purrr 抓取带有嵌套链接的多个页面的问题

Question about using rvest and purrr for scraping multiple pages with nested links

我写了下面的代码来提取 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() 函数从 table 的标题列中检索 'href' 属性 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="

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
}) 

以上代码会将 link 作为数据框中的附加列添加到语音中。

第二部分 要提取演讲文本,检索 link 的列表,然后遍历列表,打开页面,提取所需信息,存储并重复。

#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
})

此处所有数据都存储在数据框中。然后可以根据未来的意图将此数据框与上面的数据框连接起来。