马甲 | read_xml 声明错误,而 read_html 没有

rvest | read_xml claims error where read_html does not

采取以下url

URL <- "http://www.google.de/complete/search?output=toolbar&q=TDS38311DE"
doc <- read_xml(URL)

我收到以下错误:

Error: Input is not proper UTF-8, indicate encoding !
Bytes: 0xDF 0x20 0x2F 0x20 [9]

改用 read_html 一切都很好。
难道我做错了什么?为什么会出现这个错误?

首先:rvest 使用 xml2 获取内容,因此您应该在 gh 与 rvest.

包下提交任何与之相关的问题

其次,read_xml 需要一个encoding参数是有原因的,这么说"Unless otherwise specified XML documents are assumed to be in UTF-8 or UTF-16. If the document is not UTF-8/16, and lacks an explicit encoding directive, this allows you to supply a default."

XML 文件具有 specify an encoding 的能力,但是 google 的 "AJAX-y" 响应显然不是(而且它不希望你偷窃和它知道它通常被 HTML 解析引擎 [a.k.a. 浏览器] 读取,而不是 XML 解析引擎)。

rvest 曾经这样做过:

encoding <- encoding %||% default_encoding(x)

xml2::read_xml(httr::content(x, "raw"), encoding = encoding, base_url = x$url,
  as_html = as_html)

并且 default_encoding 这样做:

default_encoding <- function(x) {
  type <- httr::headers(x)$`Content-Type`
  if (is.null(type)) return(NULL)

  media <- httr::parse_media(type)
  media$params$charset
}

rvest 现在只公开 sessionresponse 对象的 read_xml 方法(在其中进行编码猜测)。

因此,您可以:

  • 在抓取之前进行一些手动反省(在阅读网站的 ToS 之后),
  • 使用 httr 获取页面并将其传递给 read_xml,或
  • 将您自己的 reader 函数连接到您的脚本中,使用相同的用法