当前位置: 代码网 > it编程>前端脚本>Python > Python爬虫XPath解析出乱码的问题及解决

Python爬虫XPath解析出乱码的问题及解决

2024年06月12日 Python 我要评论
python爬虫xpath解析出乱码请求后加上编码resp = requests.get(url, headers=headers)resp.encoding = 'gbk'python xpath解

python爬虫xpath解析出乱码

请求后加上编码

resp = requests.get(url, headers=headers)
resp.encoding = 'gbk'

python xpath解析html出现⋆解决方法 html出现{

爬网页又遇到一个坑,老是出现a乱码,查看html出现的是&#数字;这样的。

网上相关的“python字符中出现&#的解决办法”又没有很好的解决,自己继续冲浪,费了一番功夫解决了。

这算是又加深了一下我对这些iso、unicode编码的理解。故分享。

问题

用python的lxml解析html时,调用text()输出出来的结果带有a这样的乱码:

网页原页面展示:

爬取代码:

url = "xxx"
 
response = requests.request("get", url)
 
html = etree.html(response.text)
 
# 直接调用text函数
description = html.xpath('//div[@class="xxx"]/div/div//text()')
# 直接打印
for desc in description:
    print(desc)

原因

不用说自然是编码的问题。下面教大家排查和解决。

排查与解决

首先查看返回的响应是如何编码的:

response = requests.request("get", url, proxies=proxy)
# 得到响应之后,先检查一下它的编码方式
print(response.encoding)

结果如下:

然后根据这个编码的方式再来解码:

html = etree.html(response.text)
 
description = html.xpath('//div[@class="xxx"]/div/div//text()')
 
for desc in description:
    # print(desc)
    # 根据上面的结果,用iso88591来编码,再解码为utf-8
    print(desc.encode("iso-8859-1").decode("utf-8"))

结果如下:

完整代码:

url = "xxx"
 
response = requests.request("get", url)
print(response.encoding)
 
html = etree.html(response.text)
 
description = html.xpath('//div[@class="xxx"]/div/div//text()')
 
for desc in description:
    print(desc.encode("iso-8859-1").decode("utf-8"))
    # print(desc)

总结

网上有用python2流传下来的htmlparser的,还有用python3的html包的,效果都不好。

不过也有改response的编码方式的,就是这样:

url = "xxx"
 
response = requests.request("get", url)
 
# html = etree.html(response.text)
html = etree.html(response.content)  # 改用二进制编码
 
# 直接调用text函数
description = html.xpath('//div[@class="xxx"]/div/div//text()')
# 直接打印
for desc in description:
    print(desc)

也能成功解析。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com