gpt4 book ai didi

python - 来自网站的文本显示为乱码而不是希伯来语

转载 作者:太空狗 更新时间:2023-10-30 01:01:05 25 4
gpt4 key购买 nike

我正在尝试从网站获取字符串。我用 requests模块发送 GET 请求。

text = requests.get("http://example.com") #send GET requests to the website
print text.text #print the variable

但是,由于某种原因,文本显示为乱码而不是希伯来语:

<div>
<p>שרת</p>
</div>

当我用 Fiddler 嗅探流量或在浏览器中查看网站时,我看到的是希伯来语:

<div>
<p>שרת</p>
</div>

顺便说一句,html 代码包含定义编码的元标记,即utf-8。我尝试将文本编码为 utf-8 但它仍然是乱码。我尝试使用 utf-8 解码它,但它抛出 UnicodeEncodeError 异常。我在脚本的第一行声明了我正在使用 utf-8。此外,当我使用内置的 urllib 模块发送请求时也会发生此问题。

我读了Unicode HOWTO , 但仍然无法修复它。我也在这里阅读了很多线程(关于 UnicodeEncodeError 异常以及为什么希伯来语在 Python 中变成乱码)但我仍然无法修复它。

我在 Windows 机器上使用 Python 2.7.9。我正在 Python IDLE 中运行我的脚本。

提前致谢。

最佳答案

服务器未正确声明编码。

>>> print u'שרת'.encode('latin-1').decode('utf-8')
שרת

在访问text.text之前设置text.encoding

text = requests.get("http://example.com") #send GET requests to the website
text.encoding = 'utf-8' # Correct the page encoding
print text.text #print the variable

关于python - 来自网站的文本显示为乱码而不是希伯来语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29988365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com