Python XPath解析html出现⋆解决方法 html出现{解决方法

前言

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

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

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

问题

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

网页原页面展示:

爬取代码:

python 复制代码
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)

原因

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

排查与解决

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

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

结果如下:

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

python 复制代码
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"))

结果如下:

完整代码:

python 复制代码
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的编码方式的,就是这样:

python 复制代码
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)

也能成功解析。

参考文章:

Xpath编码问题解决

xpath获取标签属性乱码解决(成长日记)_xpath如何获取标签中的文本打印出来是问号-CSDN博客

相关推荐
Amo Xiang1 小时前
《100天精通Python——基础篇 2025 第18天:正则表达式入门实战,解锁字符串处理的魔法力量》
python·正则表达式·re
忆源2 小时前
【Qt】之音视频编程1:QtAV的背景和安装篇
开发语言·qt·音视频
敲键盘的小夜猫2 小时前
Python核心数据类型全解析:字符串、列表、元组、字典与集合
开发语言·python
李匠20242 小时前
C++GO语言微服务之图片、短信验证码生成及存储
开发语言·c++·微服务·golang
UpUpUp……3 小时前
HTML简单语法标签(后续实操:云备份项目)
笔记·html
apcipot_rain3 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
小彭律师3 小时前
门禁人脸识别系统详细技术文档
笔记·python
鸿业远图科技4 小时前
分式注记种表达方式arcgis
python·arcgis
别让别人觉得你做不到5 小时前
Python(1) 做一个随机数的游戏
python
巨龙之路5 小时前
C语言中的assert
c语言·开发语言