python - 使用Python和请求抓取网页时的字符集问题

标签 python encoding character-encoding

尝试下载中文页面时(根据元标记似乎是 gb2312)。我得到乱码,例如ê×××(ò) 是我运行下面的代码并在 gEdit 中打开 gb2312 格式的文件后,汉字应该在的位置。

以下是相关页面的源代码:https://gist.github.com/anonymous/27663069655db7fd7a19 - 实际网站仅适用于教育机构。

我的代码:

r = requests.post("http://example.com", data=payload, cookies=cookies)
f = open('myfile.txt', 'w')
f.write(r.text.encode('gb2312',errors="ignore"))
f.close()

页面标题:

{'content-length': '6164', 'x-powered-by': 'ASP.NET', 'date': 'Mon, 11 Mar 2013 05:11:24 GMT', 'cache-control': 'private', 'content-type': 'text/html', 'server': 'Microsoft-IIS/6.0'}

如果我尝试解码而不是编码,我会在 Python 中收到此错误:

f.write(r.text.decode('gb2312',errors="ignore"))

UnicodeEncodeError: 'ascii' codec can't encode characters in position 2017-2018: ordinal not in range(128)

最佳答案

djc@enrai http $ python
Python 2.7.3 (default, Jun 18 2012, 09:39:59)
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> rsp = urllib.urlopen('https://gist.github.com/anonymous/27663069655db7fd7a19/raw/836a5c55d0f87a2fa5edcc9a14097c945452f520/chinese.html').read()
>>> import chardet
>>> chardet.detect(rsp)
{'confidence': 0.99, 'encoding': 'utf-8'}
>>> rsp.decode('utf-8')
u'\n<HTML><HEAD>(snip)</BODY></HTML>\n'

所以,我猜不要相信字符集 header ?

关于python - 使用Python和请求抓取网页时的字符集问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15331685/

相关文章:

html - 使用 windows-1252 而不是 UTF-8 有什么问题

python - Django DynamoDB 数据库后端

node.js - Node : Request ISO-8859-1 encoded content

python - 检查列表在二维列表中的成员资格

mysql - 更改实时 MySQL 数据库上的字符集

mysql - MySQL 中的字符集配置层如何组合在一起?

html - R htmlParse XML 中的编码问题

java - 在 JSF/facelets 中访问请求参数的过滤器会导致编码错误

python - 如何使用 Python 在 Airflow DAG 中导入外部脚本?

Python Unicode 编码