首页 > python lxml中xpath解析sina只得到head

python lxml中xpath解析sina只得到head

我在用urllib2和lxml解析sina主站点,我成功获得了页面,做了编码转换(print出来看是成功的),但是xpath解析只能得到html和head。

        html = self._Encoding(html)
        page = etree.HTML(html)
        if page == None:
            self.log.error('You got a None page,may be Encoding error, %s',page)
            return (None,None)

        x = page.xpath('/html')
        print x,type(x)
        for tmp in x:
            print tmp
            print tmp.tag
            print tmp.attrib
            print tmp.text
            for i in tmp.getchildren():
                print i.text
                print i.attrib
                print i.tag

如上,我得到:

  [<Element html at 0x2a04d08>] <type 'list'>
  <Element html at 0x2a04d08>
  html
  {}


  {}
  head

写的有点乱,全部的代码在:https://github.com/tdifg/Spidey/blob/master/spider/myspider.py
关键部分在_PageHandle函数中
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
重新编辑下,意思是这样的,如下:

        x = page.xpath('/html')
        print x[0].getchildren(),'child'

应该是输出这样的:

        [<Element head at 0x2a57188>, <Element body at 0x2a57148>]

但是结果是这样的:

        [<Element head at 0x2ac0ec8>]

问题解决了,在这里记下。
问题就是我在改变了编码之后没有改变html页面的charset,而lxml根据页面做xpath解析就…所以解析不出东西。

【热门文章】
【热门文章】