r-刮擦网站时的参数意味着行的数量有所不同



我在运行代码时会遇到此错误:

Error in data.frame(date = html_text(html_nodes(pagina, ".node-post-date")),  : 
  arguments imply differing number of rows: 9, 10

在第983页中刮擦标签时,我只得到9个结果(而不是每个页面的通常10个结果(。我认为这是在发生这种情况,因为在该网页中,我要刮擦的日期之一与我使用的标签不同。

我是R的新手

这是我的代码:

#Libraries
library(rvest)
library(purrr)
library(tidytext)
library(dplyr)
url_espectador <- 'https://www.elespectador.com/search/farc?page=%d&sort=created&order=desc'
map_df(980:990, function(i) {
  pagina <- read_html(sprintf(url_espectador, i, '%s', '%s', '%s', '%s'))
  print(i)
  data.frame(title = html_text(html_nodes(pagina, ".node-title a")),
             date = html_text(html_nodes(pagina, ".node-post-date")),
             link = paste0("https://www.elespectador.com", str_trim(html_attr(html_nodes(pagina, ".node-title a"), "href"))),
             stringsAsFactors=FALSE)
  }) -> noticias_espectador

除了if语句外,还有其他解决方案吗?我要刮擦大量页面,因此我需要避免使用此行匹配问题。感谢您的帮助!

您可以使用CSS或语法添加其他类(适用于少数其他类时(。

另外,您可以选择共享父节点,测试是否存在特定的孩子,请返回NA,如果不是。这个答案显示了后者的方法。如果您使用后者,可以使用Selector .node--search-result获得合适的父节点 - 您可能会错过实际感兴趣的孩子(如在这种情况下不同的类别( - 但代码不会出错。

有第三个选项 - 在观察到的情况下,类具有公共后缀,因此您可以使用 contains(*(或ends with($(操作员使用属性=值CSS选择器,例如date = html_text(html_nodes(pagina, "[class$='post-date']"))

library(rvest)
library(purrr)
library(tidytext)
library(dplyr)
url_espectador <- 'https://www.elespectador.com/search/farc?page=%d&sort=created&order=desc'
map_df(980:990, function(i) {
  pagina <- read_html(sprintf(url_espectador, i, '%s', '%s', '%s', '%s'))
  print(i)
  data.frame(title = html_text(html_nodes(pagina, ".node-title a")),
             date = html_text(html_nodes(pagina, ".node-post-date, .field--name-post-date")),
             link = paste0("https://www.elespectador.com", str_trim(html_attr(html_nodes(pagina, ".node-title a"), "href"))),
             stringsAsFactors=FALSE)
}) -> noticias_espectador

最新更新