【问题标题】:httr - parsing xml not as text, but still specifying encodinghttr - 不将 xml 解析为文本,但仍指定编码
【发布时间】: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")(也许我在开发版中修复了它?)

标签: xml r encoding path httr


【解决方案1】:

试试:

 test <- htmlParse("http://ec.europa.eu/archives/commission_2004-2009/index_en.htm")
 res <- xpathSApply(test, "//img", xmlGetAttr, "alt")
 tail(res)
 #[1] "Slovakian"   "PDF"         "PDF"         "PDF"         "PDF - 66 KB"
#[6] "français" 

使用您的代码,(第一和第二)

 tail(res1)
 #[1] "Slovakian"   "PDF"         "PDF"         "PDF"         "PDF - 66 KB"
 #[6] "français"  

  tail(res2)
 #[1] "Slovakian"   "PDF"         "PDF"         "PDF"         "PDF - 66 KB"
 #[6] "français"  

【讨论】:

  • 谢谢。所以我想问题在于我首先使用了 GET 函数(我必须这样做才能使用我的工作代理服务器)。关于为什么会这样的任何想法?
  • @user2987808 抱歉,我不确定。
猜你喜欢
  • 2017-03-25
  • 1970-01-01
  • 2013-10-17
  • 2021-01-27
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多