跟进:如何下载 xml,不知何故 html

Follow up: How to download xml, when it somehow is html

这是对我一年前在这里提出的一个问题的跟进:How can I extract info from xml page with R

建议的解决方案工作了很长一段时间。不幸的是,在它运行顺利之后,我从未考虑过它。现在 R 向我抛出一个错误,我显然不知道如何继续。

这是我想要做的:

require(XML)
require(RCurl)

url <- "http://ws.parlament.ch/votes/councillors?affairNumberFilter=20130051&format=xml"
affairs_det <- getURL(url, .opts=c(user_agent("Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"), 
                            verbose()), asNames=TRUE)  
#This worked, but not anymore
Error in function (type, msg, asError = TRUE)  : No URL set!
In addition: Warning message:
In mapCurlOptNames(names(.els), asNames = TRUE) :
Unrecognized CURL options: output, auth_token, options, fields, headers, method, url

affairs_det_parsed <- xmlTreeParse(substr(affairs_det,4,nchar(affairs_det)), encoding = "UTF-8")

这个问题不知何故是双重的。首先,我应该如何下载文件,好像是xml,但是如果我用download.file(url, destfile="test.xml")下载它,它似乎是html?我相信 user_agent 的设置处理了...?

其次,我没有理解错误?

编辑

我想通过标签访问信息,例如 id。在 mysterios 错误之前,这也有效。

infofile <- xmlRoot(affairs_det_parsed)

#gets councillor ids
id <- getNodeSet(infofile, paste0("//councillors/councillor/id"))
id <- lapply(id, function(x) xmlSApply(x, xmlValue))
id <- sapply(id, "[[", 1)

谢谢!

原答案混合了 RCurl 和 httr 语法,很奇怪。您上面的代码段忽略了指示 httr 的使用。可能 httr 已更改但继续与自身一起使用,但没想到它会与 RCurl 一起使用。

library(httr)
x = GET(url)

检索文件。

stop_for_status(x)

检查没有错误。

xml = content(x)

获取XML内容。或者,下载到磁盘并使用 XML 解析它

t <- tempfile()
GET(url, write_disk(t))
xml = xmlParse(t)

好吧,我几乎 XML 进入了 R 而不是 HTML。我认为这会有所帮助。

XML 的解析比 HTML 更可靠(还要记住你的源服务 HTML 但有错误)XML 文件很简单,所以写xpath的会容易很多。

我首先使用命令行curl,因为我比较熟悉它。此命令行拉入 XML:

curl -H "Accept: application/xml"\
     -H "Content-Type: application/xml"\
     -X GET http://ws.parlament.ch/votes/councillors?affairNumberFilter=20130051&format=xml

我将其翻译成测试 URI 存在的 Rcurl,然后将其加载到文档中:

if(url.exists("http://ws.parlament.ch/votes/councillors?affairNumberFilter=20130051&format=xml")) 
{
    curl = getCurlHandle()
    curlSetOpt( .opts = list(httpheader = c(Accept ="application/xml", "Content-Type"="application/xml"), verbose = TRUE),curl = curl)
    doc = getURL("http://ws.parlament.ch/votes/councillors?affairNumberFilter=20130051&format=xml", curl = curl)
}

但是 xmlParse 抛出一个错误说 Error: XML content does not seem to be XML。目视检查下载的文件会发现前导垃圾字符,特别是 "。我认为这需要在进一步处理之前解决。

这很有趣,因为命令行 Curl 没有那些杂散的前导字符。

也许有更多经验的人可以更进一步。