Python 爬虫乱码问题
import requests
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0"
}
resp = requests.get("http://cmathc.cn/", headers=headers)
print(resp.text)
可以很明显看出有乱码,解决的方式非常的简单粗暴
我们发现,网络返回的字符集类型和推测出来的字符集类型是不一致的,因此我们只要将字符集类型设定为推断出来的字符集类型即可,于是
import requests
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0"
}
resp = requests.get("http://cmathc.cn/", headers=headers)
resp.encoding = resp.apparent_encoding
print(resp.text)
看图可知乱码问题得到了解决