首页 > 解决方案 > 通过 HTML 页面的 requests.get 从 lxml.html.fromstring 获取正确的 UTF-8?

问题描述

标签: pythonutf-8

解决方案


根本问题是您使用confpage.content的是confpage.text.

  • requests.Response.content为您提供原始字节(bytes在 3.x 中,str在 2.x 中),从电线上拉下来。不管是什么encoding,因为你没有使用它。
  • requests.Response.text为您提供解码的 Unicode(str在 3.x 中,unicode在 2.x 中),基于encoding.

因此,设置encoding但然后使用content不会做任何事情。如果您只是将其余代码更改为使用text而不是content(并摆脱现在decode对 Python 3 的虚假),它将起作用:

mystr = confpage.text
for line in iter(mystr.splitlines()):
  if 'Testing' in line:
    print(line)
confpagetree = LH.fromstring(confpage.text)
print(confpagetree) # <Element html at 0x7f4b7074eec0>
#print(confpagetree.text_content())
for line in iter(confpagetree.text_content().splitlines()):
  if 'Testing' in line:
    print(line)

如果您想解决每个示例的确切问题:

  • 您的第一个示例在 Python 3 中是正确的,但不是最好的方法。通过调用decode("utf-8")content由于字节恰好是 UTF-8,因此您可以正确解码它们。所以他们会正确打印出来。
  • 您的第一个示例在 Python 2 中是错误的。您只是在打印content,这是一堆 UTF-8 字节。如果您的控制台是 UTF-8(就像在 macOS 上一样,也可能在 Linux 上),这将发生。如果您的控制台是其他东西,例如 cp1252 或 Latin-1(因为它在 Windows 上,并且可能在 Linux 上),这将为您提供 mojibake。
  • 你的第二个例子也是错误的。通过将字节传递给LH.fromstring,您将强制 lxml 猜测要使用的编码,并且它会猜测 Latin-1,因此您会得到 mojibake。

推荐阅读