python在html中显示乱码怎么办
python写入html文件中文乱码问题
使用open函数将爬虫爬取的html写入文件,有时候在控制台不会乱码,但是写入文件的html中的中文是乱码的
案例分析
看下面一段代码:
# 爬虫未使用cookie from urllib import request if __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文件中
解决方案
使用open方法的一个参数,名为encoding=” “,加入encoding=”utf-8”即可
# 爬虫未使用cookie from urllib import request if __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)
运行结果
更多Python技术请关注云海天Python教程。
来源:PY学习网:原文地址:https://www.py.cn/article.html