当前位置:   article > 正文

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

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

前言

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

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

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

问题

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

网页原页面展示:

爬取代码:

  1. url = "xxx"
  2. response = requests.request("GET", url)
  3. html = etree.HTML(response.text)
  4. # 直接调用text函数
  5. description = html.xpath('//div[@class="xxx"]/div/div//text()')
  6. # 直接打印
  7. for desc in description:
  8. print(desc)

原因

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

排查与解决

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

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

结果如下:

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

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

 结果如下:

完整代码:

  1. url = "xxx"
  2. response = requests.request("GET", url)
  3. print(response.encoding)
  4. html = etree.HTML(response.text)
  5. description = html.xpath('//div[@class="xxx"]/div/div//text()')
  6. for desc in description:
  7. print(desc.encode("ISO-8859-1").decode("utf-8"))
  8. # print(desc)

总结

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

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

  1. url = "xxx"
  2. response = requests.request("GET", url)
  3. # html = etree.HTML(response.text)
  4. html = etree.HTML(response.content) # 改用二进制编码
  5. # 直接调用text函数
  6. description = html.xpath('//div[@class="xxx"]/div/div//text()')
  7. # 直接打印
  8. for desc in description:
  9. print(desc)

也能成功解析。

参考文章: 

Xpath编码问题解决

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/54369?site
推荐阅读
相关标签
  

闽ICP备14008679号