从多个网页中提取多段文本

Extracting multiple pieces of text from multiple web pages

此代码的第一部分(最多 "pages")成功检索了我要从中抓取的页面。然后,我正在努力寻找一种方法来提取带有相关日期的文章文本片段作为数据框。

我得到:

UseMethod("read_xml") 错误: 没有适用于 'read_xml' 的方法应用于 class "c('xml_document', 'xml_node')"

的对象

也欢迎任何关于优雅、清晰和效率的指导,因为这是个人学习。

library(rvest)
library(tidyverse)
library(plyr)
library(stringr)

llply(1:2, function(i) {

  read_html(str_c("http://www.thetimes.co.uk/search?p=", i, "&q=tech")) %>% 
    html_nodes(".Headline--regular a") %>% 
    html_attr("href") %>%
    url_absolute("http://www.thetimes.co.uk")

}) -> links

pages <- links %>% unlist() %>% map(read_html)

map_df(pages, function(x) {

  text = read_html(x) %>% 
    html_nodes(".Article-content p") %>% 
    html_text() %>% 
    str_extract(".+skills.+")

  date = read_html(x) %>% 
    html_nodes(".Dateline") %>% 
    html_text()

}) -> article_df

很好,你快到了!这里有两个错误:

  1. 变量pages已经包含解析的html代码。因此,在单个页面(即 map_df 内)再次应用 read_html 无效。这是您收到的错误消息。

  2. map_df中的函数不正确。由于没有明确的 return 最后计算的值是 returned,即 date。变量 text 完全被遗忘了。您必须将这两个变量打包在一个数据框中。

以下为固定代码

article_df <- map_df(pages, function(x) {
  data_frame(
    text = x %>% 
      html_nodes(".Article-content p") %>% 
      html_text() %>% 
      str_extract(".+skills.+"),

    date = x %>% 
      html_nodes(".Dateline") %>% 
      html_text()
  )
})

还有一些关于代码本身的评论:

  • 我认为用<-代替->更好。这样一来,人们可以更容易地找到分配变量的位置,如果使用 'speaking variable names',则更容易理解代码。
  • 我更喜欢使用包 purrr 而不是 plyrpurrrtidyverse 包的一部分。因此,您可以简单地使用 map 而不是函数 llply。在 purrrplyr 上有一个 nice article

links <- map(1:2, function(i) {
  read_html(str_c("http://www.thetimes.co.uk/search?p=", i, "&q=tech")) %>% 
    html_nodes(".Headline--regular a") %>% 
    html_attr("href") %>%
    url_absolute("http://www.thetimes.co.uk")
})