【问题标题】:rvest error: "Error in class(out) <- "XMLNodeSet" : attempt to set an attribute on NULL"rvest 错误:“类中的错误(输出)<-”XMLNodeSet”:尝试将属性设置为 NULL”
【发布时间】:2014-12-29 10:05:10
【问题描述】:

我正在尝试使用新的 rvest 包抓取一组网页。它适用于大多数网页,但是当没有特定字母的表格条目时,会返回错误。

# install the packages you need, as appropriate
install.packages("devtools")
library(devtools)
install_github("hadley/rvest")
library(rvest)

此代码可以正常工作,因为网页上有字母 E 的条目。

# works OK
url <- "https://www.propertytaxcard.com/ShopHillsborough/participants/alph/E"
pg <- html_session(url, user_agent("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0"))
pg %>% html_nodes(".sponsor-info .bold") %>% html_text()

这不起作用,因为网页上没有字母 F 的条目。错误消息是“类中的错误(输出)

# yields error message
url <- "https://www.propertytaxcard.com/ShopHillsborough/participants/alph/F"
pg <- html_session(url, user_agent("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0"))   
pg %>% html_nodes(".sponsor-info .bold") %>% html_text()    

任何建议。提前致谢。

【问题讨论】:

    标签: r web-scraping rvest


    【解决方案1】:

    您总是可以将pg...html_nodes...html_text 包装在try 中,然后测试该类:

    tmp <- try(pg %>% html_nodes(".sponsor-info .bold") %>% html_text(), silent=TRUE)
    
    if (class(tmp) == "character") {
      print("do stuff")
    } else {
      print("do other stuff")
    }
    

    编辑:另一种选择是使用boolean() XPath 运算符并以这种方式进行测试:

    html_nodes_exist <- function(rvest_session, xpath) {
    
      xpathApply(content(rvest_session$response, as="parsed"), 
                 sprintf("boolean(%s)", xpath))
    
    }
    
    pg %>% html_nodes_exist("//td[@class='sponsor-info']/span[@class='bold']")
    

    如果这些节点存在则返回TRUE,如果不存在则返回FALSE(该函数需要泛化以能够使用session["HTMLInternalDocument" "HTMLInternalDocument" "XMLInternalDocument" "XMLAbstractDocument"] 对象并同时使用这两个CSS 选择器作为 XPath,但这是一种避免 try 的方法。

    【讨论】:

    • 仅供参考,最新版本的xml2 有更新的方法来处理这个问题。我明天会发布更新。
    猜你喜欢
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    相关资源
    最近更新 更多