2015-05-01 134 views
5

我试图从网站获取字符串。我使用requests模块发送GET请求。来自网站的文本显示为乱码而不是希伯来文

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

然而,出于某种原因,该文本将出现在乱语,而不是希伯来语:当我嗅出交通与小提琴手或查看网站在浏览器中

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

艰难,我看到它在希伯来语:

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

顺便提一下,所述html代码包含的元标签定义的编码,这是utf-8。 我试图编码文本到utf-8,但它仍然在胡言乱语。我试图使用utf-8对其进行deocde,但它抛出了UnicodeEncodeError异常。 我声明我在脚本的第一行使用了utf-8。 此外,当我通过内置urllib模块发送请求时,问题也会发生。

我读了Unicode HOWTO,但仍无法解决它。我还在这里阅读了很多主题(包括关于UnicodeEncodeError异常以及为什么希伯来语会变成Python中的乱码),但我仍然无法解决它。

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

在此先感谢。

+0

您应该使用.content代替文字 –

回答

6

服务器没有正确声明编码。

>>> 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 
+0

非常感谢!我永远不会找到它自己。再次感谢! – ohad987