Python 读取网页内容 乱码问题

来源:互联网 发布:怪物猎人ol数据库 编辑:程序博客网 时间:2024/06/06 07:04

踩坑记录:
从目标url获取的内容写入txt包含乱码(读取的时候使用了utf-8)
于是追溯发现是response的内容就已经是乱码了
所以修改response内容的encoding然后再写入txt

从目标url得到response之后可以使用
print content.encoding
查看当前response内容的编码
然后如果直接输出中包含乱码,
可以通过
content.encoding = ‘utf-8’
指定为utf-8编码
同时在.py文件顶部也可以添加
# -- coding: utf-8 --

例子:
targetUrl = ‘http://www.mgtv.com’
content = requests.get(targetUrl)
dataFile = open(fileName, ‘w’)
#print content.encoding
content.encoding = ‘utf-8’
temp = content.text
dataFile.write(temp)
dataFile.close()

0 0