贴吧爬虫出现错误:ValueError: Unicode strings with encoding declaration are not supported. Please use bytes i

本文介绍了一个关于使用Python请求网页内容并解析时遇到的Unicode字符串错误问题。具体来说,当从URL获取页面内容并尝试将其转换为Element对象时,出现了不支持带有编码声明的Unicode字符串的错误。文章详细介绍了如何通过调整获取网页内容的方式从返回二进制数据而不是文本数据来解决此问题。

一、原因

    def get_page_from_url(self, url):
        response = requests.get(url, headers=self.headers)
        # 这个位置可能会有问题(去掉了decode())
        # return response.content
        return response.content.decode()
.......
    def get_datas_from_page(self, page):
        '''提取页面中数据'''
        # 把page转换为Element对象
        # ValueError: Unicode strings with encoding declaration are not supported.
        # 解决方案; 就是要传入二进制数据
        html = etree.HTML(page)

二、解决方案:

    def get_page_from_url(self, url):
        response = requests.get(url, headers=self.headers)
        # 这个位置可能会有问题(去掉了decode())
        return response.content
        # return response.content.decode()

    def get_datas_from_page(self, page):
        '''提取页面中数据'''
        # 把page转换为Element对象
        # ValueError: Unicode strings with encoding declaration are not supported.
        # 解决方案; 就是要传入二进制数据
        html = etree.HTML(page)
      ........

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值