Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x lxml和错误的源代码编码_Python 3.x_Python Requests_Lxml - Fatal编程技术网

Python 3.x lxml和错误的源代码编码

Python 3.x lxml和错误的源代码编码,python-3.x,python-requests,lxml,Python 3.x,Python Requests,Lxml,下面的网页没有正确编码,但我正在构建一个无论如何都需要正确处理的客户端(服务器上没有控制)。显然服务器没有提供UTF-8。如何使用lxml和请求对结果进行正确编码来纠正这个问题 from lxml import html from lxml import etree import requests url = 'https://immobilier-segre.nestenn.com/maison-de-plain-pied-de-97-m2-plein-centre-de-segre-ref

下面的网页没有正确编码,但我正在构建一个无论如何都需要正确处理的客户端(服务器上没有控制)。显然服务器没有提供UTF-8。如何使用lxml和请求对结果进行正确编码来纠正这个问题

from lxml import html
from lxml import etree
import requests

url = 'https://immobilier-segre.nestenn.com/maison-de-plain-pied-de-97-m2-plein-centre-de-segre-ref-33659881'
r = requests.get(url)
tree = html.fromstring(r.content)

with open('file.html', 'wb') as file:
    #write the pretty XML to a file
    file.write(etree.tostring(tree, pretty_print=True))
在这个URL上,它给出了“Franchisé而不是“Franchisé”。如果url指向正确编码的站点,我没有问题,但是对于上面的url,我有问题,我想在客户端更正这个问题,以便在所有情况下以正确编码保存html文件


我的猜测是,该页面在服务器端没有正确编码,因此希望在客户端检测并更正该问题。

为什么要尝试解析r.content(二进制)而不是r.text?在后一种情况下,您的示例在我的系统上呈现得很好,而在前一种情况下,我确实看到了编码问题Eli Korvigo 11月27日11:16编码不正确。它显示的是“Franchisé而不是“Franchisé”。为什么您试图解析
r.content
(二进制)而不是
r.text
?在后一种情况下,您的示例在我的系统上呈现得很好,而在前一种情况下,我确实看到了编码问题。谢谢,这解决了它。我在lxml api中寻找答案。。。使用r.text确实为我提供了我所期望的