【发布时间】:2015-12-16 04:19:12
【问题描述】:
这是我一年前在这里提出的一个问题的后续: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)
谢谢!
【问题讨论】:
-
以下对我有用。
affairs_det <- getURL(url, asNames=TRUE);,尽管会引发您提到的警告。事实上,即使download.file(url,"test.xml")也能正常工作。并且下载的xml被解析得很好。不确定相同的解析xml是否符合您的目的。 -
@Frash 这确实会下载内容,但不幸的是没有标签。
-
"似乎是 XML.." 它不是。 ws.parlament.ch/votes/… 生成 XML 而不是 HTML。将其加载到浏览器中,然后查看页面源代码。
-
但是在 R 中,它是 HTML。即使您的请求是明确格式=XML。奇怪的。如果你能把它作为 XML 导入 R,你会更好。有时 HTML 可能难以解析。我通过validator.w3.org/… 运行该页面并收到警告。