【发布时间】:2014-08-27 07:34:42
【问题描述】:
我正在尝试使用 httr 包抓取以 UTF-8 编码的网站,但显然该包的 content 函数仅允许在您将网站解析为文本时指定编码。不幸的是,我无法将其解析为文本,因为我想在之后对其使用 xpath 查询。这是一个例子:
library(XML)
library(httr)
page <- GET("http://ec.europa.eu/archives/commission_2004-2009/index_en.htm")
test <- content(page, as = "parsed")
# Get a list of names, many of which contain non-standard characters
xpathSApply(test, "//img", xmlGetAttr, "alt")
# This gives the correct encoding, but outputs a character vector,
# on which I cannot use xpath queries
test <- content(page, as = "text", encoding = "utf-8")
更新:
# htmlParse returns a parsed document, but the non-standard characters are
# not properly encoded, i.e. the result is the same whether or not I specify the
# "encoding" argument
test <- htmlParse(page, encoding = "UTF-8")
# Non-standard characters in names still not properly encoded
xpathSApply(test, "//img", xmlGetAttr, "alt")
【问题讨论】:
-
“不起作用”是什么意思?因为我得到了一个结果,尽管是一个 access denied 消息,但它仍然是一个已解析的 XML 文档。
-
我也用
content(page, as="parsed")[httr v0.4.0.99, R3.1.1, OS X] 和xpathSApply给了我一个包含名称的113元素向量来自imgalt标签。注意:当您确实让它工作时,如果您只想要委员的姓名,您应该将 XPath 更改为//img[@class='comm_img']。 -
谢谢,感谢您的帮助。我使用相同的 httr 和 R 版本,但我在 Windows 机器上。你认为它有什么可以做的吗?
-
为什么您认为您不能为
as = "parsed"提供编码?这对我有用:content(page, as = "parsed", encoding = "utf-8")(也许我在开发版中修复了它?)