requests的content与text导致lxml的解析问题

我使用requests获取了新浪微博的源代码,通过lxml库的etree.HTML来处理一段网页源代码,从而生成一个可以被xpath解析的对象。

selector = etree.HTML(html)

遇到报错:

selector = etree.HTML(html)
  File "lxml.etree.pyx", line 2953, in lxml.etree.HTML (src\lxml\lxml.etree.c:66734)
  File "parser.pxi", line 1780, in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:101591)
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

根据报错信息推测,可能是因为不支持编码声明的Unicode字符串。Google发现这个问题在2012年就已经有人提交给作者了,但是一直没有被修复。地址在-> https://gist.github.com/karlcow/3258330

不过下面的人也给出了解决办法:

html = bytes(bytearray(html, encoding='utf-8'))
selector = etree.HTML(html)

首先将源代码转化成比特数组,然后再将比特数组转化成一个比特对象。这样就可以绕过这个bug。

然而,又有人认为这不是一个bug, 所以一直没有被修复。这是由于,我获取源代码是使用r.text

html = requests.get('xxxxxx',cookies=cookies).text

而如果使用r.content:

html = requests.get('xxxxxx',cookies=cookies).content

就不会报错。

那r.text与r.content有什么区别呢?分析requests的源代码发现,r.text返回的是Unicode型的数据,而使用r.content返回的是bytes型的数据。也就是说,在使用r.content的时候,他已经只带了

html = bytes(bytearray(html, encoding='utf-8'))

这样一个转化了。

posted on 2017-02-28 10:57  吃咯  阅读(832)  评论(0编辑  收藏  举报

导航