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博客

相关推荐
郝学胜-神的一滴7 分钟前
Linux下,获取子进程退出值和异常终止信号
linux·服务器·开发语言·c++·程序人生
AI科技星21 分钟前
张祥前统一场论动量公式P=m(C-V)误解解答
开发语言·数据结构·人工智能·经验分享·python·线性代数·算法
海琴烟Sunshine25 分钟前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode
ithicker33 分钟前
Pycharm+Deepseek结合使用Continue插件无法返回中文产生乱码
ide·python·pycharm
CodeByV41 分钟前
【C++】继承
开发语言·c++
棉猴1 小时前
《pygame中Sprite类实现多帧动画》注-通过多张序列帧显示动画2-1
python·游戏·pygame·游戏编程
权泽谦1 小时前
用 Python 做一个天气预报桌面小程序(附源码 + 打包与部署指导)
开发语言·python·小程序
ftpeak1 小时前
《Rust+Slint:跨平台GUI应用》第八章 窗体
开发语言·ui·rust·slint
森语林溪1 小时前
大数据环境搭建从零开始(十七):JDK 17 安装与配置完整指南
java·大数据·开发语言·centos·vmware·软件需求·虚拟机
“负拾捌”1 小时前
LangChain提示词模版 PromptTemplate
python·langchain·prompt