【发布时间】:2013-03-11 05:21:11
【问题描述】:
尝试下载中文页面时(根据元标记显示为 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)
【问题讨论】:
标签: python encoding character-encoding