
使用open函数将爬虫爬取的html写入文件,有时候在控制台不会乱码,但是写入文件的html中的中文是乱码的
案例分析
看下面一段代码:
# 爬虫未使用cookiefrom urllib import requestif __name__ == '__main__':
url = "http://www.renren.com/967487029/profile"
rsp = request.urlopen(url)
html = rsp.read().decode() with open("rsp.html","w")as f: # 将爬取的页面
print(html)
f.write(html)看似没有问题,并且在控制台输出的html也不会出现中文乱码,但是创建的html文件中
立即学习“Python免费学习笔记(深入)”;

解决方案
使用open方法的一个参数,名为encoding=” “,加入encoding=”utf-8”即可
# 爬虫未使用cookiefrom urllib import requestif __name__ == '__main__':
url = "http://www.renren.com/967487029/profile"
rsp = request.urlopen(url)
html = rsp.read().decode() with open("rsp.html","w",encoding="utf-8")as f: # 将爬取的页面
print(html)
f.write(html)运行结果

感谢大家的阅读,希望大家收益多多。
本文转自: https://blog.csdn.net/qq_40147863/article/details/81746445
推荐教程:《python教程》
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号