python爬虫结果写入html时编码错误

html一般采用的都是utf-8的编码,但是默认的编码时GBK。

 1. open方法时采用 encoding=“utf-8

 

fout = open("output.html",mode="w",encoding="utf-8")
结果:可以生成html文件但是打开后乱码如下

 

2. 对中文语句后加 .encode(“utf-8”)

fout.write("<td>%s</td>"% data["title"].encode("utf-8"))
 结果:

 乱码如下

 3. 如果采用format方法括号位置不对还会出现报错

 

 fout.write("<td>{}</td>".format(data["title"]).encode("utf-8"))

TypeError: write() argument must be str, not bytes

解决方法

 1. html文件前方写入"<meta charset="utf-8">

  (浏览器也需要先规定编码格式,此语句可在网页源代码最始端找到)

 2. 设置encoding参数为“utf-8”,不使用 .encode()

代码如下:

 

def output_html(self):
        fout = open("output.html",mode="w",encoding="utf-8")
        fout.write("<meta charset='utf-8'>")
        fout.write("<html>")
        fout.write("<body>")
        fout.write("<table>")

        for data in self.datas:
            fout.write("<tr>")
            # fout.write("<td>%s</td>"% (data["title"]))    
            fout.write("<td>{}</td>".format(data["title"]))
            fout.write("</tr>")

        fout.write("</table>")
        fout.write("</body>")
        fout.write("</html>")

        fout.close()











                
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值