pycharm在抓取网页后网页中文乱码
抓取网页代码显示乱码
有问题的代码
from urllib.request import urlopen
url="http://www.baidu.com"
resp=urlopen(url)
with open("baidu.html",mode="w") as f:
f.write(resp.read().decode("utf-8"))
网页运行结果
问题解决
通过上网查找各种乱码解决方案,最终通过得到结果是decode函数中没有接收数据格式的参数,所以“utf-8”不应该写在decode中,应该在open函数中添加encoding=“utf-8”。
from urllib.request import urlopen
url="http://www.baidu.com"
resp=urlopen(url)
with open("baidu.html",mode="w",encoding="utf-8") as f:
f.write(resp.read().decode())