python抓取网页并写到本地文件中,出现乱码问题的关键有两处:
- 抓取网页数据后是否正确解码
- 正确解码后的html字符串写入文件时是否正确编码
要解决这两个问题,首先要知道该网页是如何编码的,先看看下面代码:
import requests
head = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) Firefox/21.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,zh-CN,zh;q=0.9"
}
url = 'http://2018.ip138.com/ic.asp'
resp=requests.get(url, headers=head,timeout=15)
print(resp.headers['content-type'])
print(resp.encoding)
print(resp.apparent_encoding)
print(requests.utils.get_encodings_from_content(resp.text))
输出结果:
这里的apparent_encoding是响应消息头里设置的编码格式,最后一个是html源码里设置编码格式,这两个我观察是一样的(不确定有没有不一样的,如果不一样,我觉得网页直接打开可能就是乱码),这里的apparent_encoding就是网页数据的编码格式,我们只要使用apparent_encoding来解码和编码,一般就不会出现乱码了。
使用方法如下:
resp = requests.get(url, headers=head,timeout=15)
resp.encoding=resp.apparent_encoding #设置解码方式
html_source=resp.text #这里会用设置的解码方式解码
print(html_source) #正确解码后直接打印也不会出现乱码
resp.close()
if html_source:
#将html写文件时设置文件编码方式,因为和html里设置的编码格式一样,所以直接打开就不会出现乱码了
with open('test.htm', mode='a+', encoding=resp.apparent_encoding) as file:
file.write(html_source)
最后希望我的方法可以帮助大家解决乱码问题。