Python3.x 爬虫爬取GB2312编码的网页出现乱码的解决方式

用Python3.x抓取GB2312编码方式的网站很容易出现乱码,原代码如图所示:

import requests
res = requests.get('http://www.jjwxc.net/onebook.php?novelid=1231454&chapterid=1')
res.encoding = res.apparent_encoding 
novel = res.text
res.close()
with open('test1.txt', mode='a+',encoding='utf-8') as file:
        file.write(novel) #生成txt文件,不是乱码

按照以上代码可以得出非乱码的txt格式的源代码,但无论是将txt改后缀成html还是按照如下代码直接爬出html文件,网页都显示为乱码

import requests
res = requests.get('http://www.jjwxc.net/onebook.php?novelid=1231454&chapterid=1')
res.encoding = res.apparent_encoding
novel = res.text
res.close()
with open('test1.html', mode='a+',encoding='utf-8') as file:
        file.write(novel) #直接生成html文件,网页为乱码

本人在网上查阅许多资料,均只能使生成的txt文件非乱码,而html文件依然是乱码,经过研究,增加以下代码:res8 =novel.encode(res.apparent_encoding,"ignore").decode(res.apparent_encoding,"ignore")可以成功爬取html文件。
最终成功的代码如下:

import requests
res = requests.get('http://www.jjwxc.net/onebook.php?novelid=1231454&chapterid=1')
res.encoding = res.apparent_encoding
novel = res.text
res.close()
# 增加以下代码,对源代码进行正确地编码和解码,从而避免乱码
res8 = novel.encode(res.apparent_encoding,"ignore").decode(res.apparent_encoding,"ignore") 
with open('test1.html', mode='a+') as file:
        file.write(res8)

需要注意若不添加“ignore”,程序将会报错:
UnicodeEncodeError: 'gb2312' codec can't encode character '\ufffd' in position 65885: illegal multibyte sequence
这是因为某些字符无法被gb2312编码,从而导致程序报错,只需忽略这些字符便可

参考:
Python学习笔记(一)转码问题的解决的解决方法:“ignore”
python3 爬虫抓取网页出现乱码问题解决方法

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值