为什么我用pythen爬取百度显示汉字乱码?

img

获取requests.get()请求数据之后要先用 res.encoding='utf-8' 设置内容的编码再取 res.text 内容

res=requests.get(f'http://www.xxxxxxxx',headers=head)
res.encoding='utf-8' 
html = res.text

在requests.get()之后加上一行代码,即可解决汉字乱码问题:res.encoding=res.apparent_encoding

from urllib.request import urlopen

url = "http://www.baidu.com" resp = urlopen(url) with open("mybaidu.html", mode="w") as f: f.write(resp.read().decode("utf-8")) print("over")