python - 通过 HTML 页面的 requests.get 从 lxml.html.fromstring 获取正确的 UTF-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。
推荐阅读
- anylogic - 如何使用来自 pedSource 的吸引子使行人出现在 AreaNode
- json - Pyspark:从涉及数组列的 Json Schema 创建 Schema
- c++ - 最后一个字符行编辑
- php - 如何实现对单字段单列中以逗号分隔的多条记录的搜索查询?
- python - 如何从 Python 中的另一个项目导入模块?
- c++ - 缓冲区用不需要的数据填充 char 数组中的最后一个空格
- c# - ASP.NET Core 2.2 Web API 在 IIS 上托管后给出 404
- bash - 在linux上安装包时如何绕过用户确认
- javascript - 需要多次关闭警报框
- javascript - 如何防止滚动上的更改检测?(角)