python写入html文件中文乱码问题

使用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文件中

ba7eb27c8a76a73427692c57650df14.png

解决方案

使用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)

运行结果

39353137a8f9ac7f0e3fac26e375b21.png

感谢大家的阅读,希望大家收益多多。

本文转自: https://blog.csdn.net/qq_40147863/article/details/81746445


如何解决python写入html文件中乱码的现象(图文详解)