Rvest刮错误

his*_*eim 1 r web-scraping rvest

这是我正在运行的代码

library(rvest)

rootUri <- "https://github.com/rails/rails/pull/"
PR <- as.list(c(100, 200, 300))
list <- paste0(rootUri, PR)
messages <- lapply(list, function(l) {
  html(l)
})
Run Code Online (Sandbox Code Playgroud)

直到这一点它似乎工作正常,但当我尝试提取文本时:

html_text(messages)
Run Code Online (Sandbox Code Playgroud)

我明白了:

Error in xml_apply(x, XML::xmlValue, ..., .type = character(1)) : 
  Unknown input of class: list
Run Code Online (Sandbox Code Playgroud)

试图提取特定元素:

html_text(messages[1])
Run Code Online (Sandbox Code Playgroud)

不能这样做......

Error in xml_apply(x, XML::xmlValue, ..., .type = character(1)) : 
  Unknown input of class: list
Run Code Online (Sandbox Code Playgroud)

所以我尝试了另一种方式:

html_text(messages[[1]])
Run Code Online (Sandbox Code Playgroud)

这似乎至少得到了数据,但仍然没有成功:

Error in UseMethod("xmlValue") : 
  no applicable method for 'xmlValue' applied to an object of class "c('HTMLInternalDocument',     'HTMLInternalDocument', 'XMLInternalDocument', 'XMLAbstractDocument')"
Run Code Online (Sandbox Code Playgroud)

如何从列表中的每个元素中提取文本材料?

pet*_*ner 5

您的代码有两个问题.在这里查看有关如何使用该包的示例.

1.你不能只使用所有功能.

  • html() 用于下载内容
  • html_node() 用于从下载的页面内容中选择节点
  • html_text() 用于从先前选择的节点中提取文本

因此,要下载其中一个页面并提取html节点的文本,请使用以下命令:

library(rvest)
Run Code Online (Sandbox Code Playgroud)

老派风格:

url          <- "https://github.com/rails/rails/pull/100"
url_content  <- html(url)
url_mainnode <- html_node(url_content, "*")
url_mainnode_text <- html_text(url_mainnode)
url_mainnode_text
Run Code Online (Sandbox Code Playgroud)

... 或这个 ...

难以读懂的老派风格:

url_mainnode_text  <- html_text(html_node(html("https://github.com/rails/rails/pull/100"), "*"))
url_mainnode_text
Run Code Online (Sandbox Code Playgroud)

... 或这个 ...

magritr-piping风格

url_mainnode_text  <- 
  html("https://github.com/rails/rails/pull/100") %>%
  html_node("*") %>%
  html_text()
url_mainnode_text
Run Code Online (Sandbox Code Playgroud)

2.使用列表时,您必须将功能应用于列表,例如 lapply()

如果您想批量处理多个URL,可以尝试这样的方法:

  url_list    <- c("https://github.com/rails/rails/pull/100", 
                   "https://github.com/rails/rails/pull/200", 
                   "https://github.com/rails/rails/pull/300")

  get_html_text <- function(url, css_or_xpath="*"){
      html_text(
        html_node(
          html("https://github.com/rails/rails/pull/100"), css_or_xpath
        )
      )
   }

lapply(url_list, get_html_text, css_or_xpath="a[class=message]")
Run Code Online (Sandbox Code Playgroud)