Skip to main content
 首页 » 编程设计

python之从 python 向带有 windows-1251 编码的页面发送请求

2025年05月04日14mate10pro

我需要获取页面源 (html) 并将其转换为 uft8,因为我想在此页面中找到一些文本(例如,如果 page_source 中有“my_same_text”:则...)。此页面包含俄语文本(сyrillic 符号)和此标记

<meta http-equiv="Content-Type" content="text/html; charset=windows-1251"> 

我使用 flask,并请求 python 库。 我发送请求 source = requests.get('url/')

if 'сyrillic symbols' in source.text: ... 

我找不到我的文字,这是由于编码 我如何将文本转换为 utf8?我尝试了 .encode() .decode() 但它没有帮助。

请您参考如下方法:

让我们用 meta 标签中给出的 windows-1251 字符集和一些俄语废话文本创建一个页面。当然,我将它作为 windows-1251 文件保存在 Sublime Text 中。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
 <head> 
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1251"> 
 </head> 
 <body> 
  <p>Привет, мир!</p> 
 </body> 
</html> 

您可以使用 a little trick在 requests 库中:

If you change the encoding, Requests will use the new value of r.encoding whenever you call r.text.

事情是这样的:

In [1]: import requests 
 
In [2]: result = requests.get('http://127.0.0.1:1234/1251.html') 
 
In [3]: result.encoding = 'windows-1251' 
 
In [4]: u'Привет' in result.text 
Out[4]: True 

瞧!

如果它对您不起作用,还有一种稍微丑陋的方法。

你应该看看网络服务器发送给你的是什么编码。

可能响应的编码实际上是cp1252(也称为ISO-8859-1),或者其他什么,但utf8都不是 或 cp1251。它可能会有所不同并取决于网络服务器!

In [1]: import requests 
 
In [2]: result = requests.get('http://127.0.0.1:1234/1251.html') 
 
In [3]: result.encoding 
Out[3]: 'ISO-8859-1' 

所以我们应该相应地重新编码。

In [4]: u'Привет'.encode('cp1251').decode('cp1252') in result.text 
Out[4]: True 

但这对我来说看起来很难看(另外,我不擅长编码,而且它根本不是最好的解决方案)。我会使用 requests 本身重新设置编码。