尝试下载中文页面时(根据元标签显示为gb2312)。我收到乱码符号ê×××(ò)在我运行下面的代码之后应该是中文字符,并在gEdit中以gb2312格式打开文件。使用Python和请求抓取网页时的字符集问题
以下是有问题页面的源代码: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)