rvest中的html与XML中的htmlParse相对应

时间:2015-06-17 16:58:37

标签: xml r rvest

如下面的代码所示,html包中的rvest使用htmlParse包中的XML。 。

html
function (x, ..., encoding = NULL) 
{
    parse(x, XML::htmlParse, ..., encoding = encoding)
}
<environment: namespace:rvest>

htmlParse
function (file, ignoreBlanks = TRUE, handlers = NULL, replaceEntities = FALSE, 
    asText = FALSE, trim = TRUE, validate = FALSE, getDTD = TRUE, 
    isURL = FALSE, asTree = FALSE, addAttributeNamespaces = FALSE, 
    useInternalNodes = TRUE, isSchema = FALSE, fullNamespaceInfo = FALSE, 
    encoding = character(), useDotNames = length(grep("^\\.", 
        names(handlers))) > 0, xinclude = TRUE, addFinalizer = TRUE, 
    error = htmlErrorHandler, isHTML = TRUE, options = integer(), 
    parentFirst = FALSE) 
.....

所以,对于以下网址:

 myurl<-"http://www.nepalstock.com.np/"
parse_XML<-htmlParse(myurl) #runs without error
parse_rvest<-html(myurl) # throws out the Internal Sever error
Error in parse.response(r, parser, encoding = encoding) : 
  server error: (500) Internal Server Error

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

从基础httr::GET请求重置默认用户代理,然后它可以工作:

library(httr)
library(rvest)
parse_rvest <- html(myurl, add_headers("User-Agent" = "myagent"))

parse_rvest <- html(myurl, user_agent("myagent"))

请注意,出于调试目的,您可以将verbose()添加到html(...)

添加:

使用新的rvest / xml2 / curl组合,它应该如下所示:

library(xml2)
library(rvest)
library(curl)
parse_rvest <- curl(myurl, handle = new_handle("useragent" = "myua")) %>%
               read_html()