[229]python3的requests类抓取中文页面出现乱码的解决办法

image.png

这种乱码现象基本上都是编码造成的,我们要转到我们想要的编码,先po一个知识点,嵩天老师在Python网络爬虫与信息提取说到过的:response.encoding是指从HTTP的header中猜测的响应内容编码方式,如果header中不存在charset,则默认编码为ISO-8859-1 ,这样一来某些不规范的服务器返回就必然乱码了;response.apparent_encoding是指从内容中分析出的响应内容编码方式。requests内部的 utils 也提供了一个从返回 body 获取页面编码的函数get_encodings_from_content,这样如果服务器返回的头不含 Charset,再通过 get_encodings_from_content 就可以知道页面的正确编码了。下面是调试的过程:

import requests
from requests.exceptions import RequestException

def get_one_page(url):
    try:
        response=requests.get(url)
        if response.status_code == 200:
            #print(response.text)
            print(response.encoding)
            print(response.apparent_encoding)
            r=response.text
            print(requests.utils.get_encodings_from_content(r)[0])
            a=r.encode('ISO-8859-1').decode(requests.utils.get_encodings_from_content(r)[0])
            print(a)
            print('------------------------------------')
            b = r.encode('ISO-8859-1').decode(response.apparent_encoding)
            print(b)
        return None
    except RequestException:
        return None

def main():
    url = 'http://www.mh160.com/'
    get_one_page(url)

if __name__=='__main__':
        main()

看图!看图!看图!
image.png

# response=requests.get(skip_url,headers=self.headers)
# # print(response.text.encode('ISO-8859-1').decode('utf-8'))
#如果出现乱码,可以直接写下面的通用转换
# html=etree.HTML(response.text.encode(response.encoding).decode(response.apparent_encoding))

如果python抓取网页后用decode解码,报错信息如下:

UnicodeDecodeError: ‘gb2312’ codec can’t decode byte 0xb0 in position 18020: illegal multibyte sequence

推测是网页数据中有错误的字符无法解码,decode有参数errors,设置一下就好啦~

html=etree.HTML(response.text.encode(response.encoding).decode(response.apparent_encoding,errors = 'ignore'))

来源:https://www.jianshu.com/p/b535a9434120

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值