一个网页抽取的错误(使用lxml.html.document_fromstring)

标签:   lxml.html , lxml , 网页内容抽取

在使用lxml抽取网页内容的时候发现一个错误:网页内容抽取的不完整,只抽取了一部分满足条件的内容出来。困惑了我好久。终于查找出来。记录如下:

先来小结:

     1、lxml.html能够处理任意编码的原始字符串,即使不进行转码它也可能 抽取成功。

     2、(猜测)lxml.html内部应该会对字符串进行编码转化,如果出错则不

     3、传入lxml.html.document_fromstring的content最好是unicode的,否则抽取结果会异常,跟我一样。因此可以先做一个变换content=content.decode(‘encoding’, ‘ignore’)。(加上ignore的话可以在忽略报错)

     4、如果不能确定编码的话可以尝试使用chardet模块。这事一个开源的字符编码自动检测模块,基于python实现。使用easy_install就可以很轻松的安装它。(官网地址是http://chardet.feedparser.org/ )

测试过程

>>> import urllib2
>>> import lxml.html as HTML
>>> import chardet
>>> import sys

>>> menuurl = u'http://www.qidian.com/BookReader/1209977.aspx'
>>> req = urllib2.Request(menuurl)
>>> the_page = urllib2.urlopen(req).read()

#1、不做任何转码
>>> doc = the_page #the_page 是网页的原始字符串
>>> root = HTML.document_fromstring(doc)
>>> tnodes = root.xpath("//div[@id='content']//div[@class='box_cont']//a" )
>>> len(tnodes) #说明,tnodes是章节内容的节点,有多少章就有tnodes的长度就是多少
475
# 说明:此时抽取出来的节点数只有不到真实数目的1/2。异常!

#2、转化成unicode
>>> doc = the_page.decode('gb2312' , 'ignore' )
>>> root = HTML.document_fromstring(doc)
>>> tnodes = root.xpath("//div[@id='content']//div[@class='box_cont']//a" )
>>> len(tnodes)
1161
# 说明:此与实际情况一致。正确。

#查看出错位置(怀疑解码过程出错,试验之)
>>> doc = the_page.decode('gb2312' )
Traceback (most recent call last):
File "" , line 1, in
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 163806-163807: illegal multibyte sequence
# 说明:打出原文的话发现出错点正好是“第四百三十四章”附近;可以由此判断1不做任何转码就把字符串喂给lxml

顺便送上lxml.html的文档:http://codespeak.net/lxml/lxmlhtml.html

本文标签:   爬虫   lxml   lxml.html   网页内容抽取  
本文转自: http://www.juziblog.com/?p=320001&code=ag16aGVuZ3BpbmcyMDExcg0LEgVFbnRyeRiBxBMM

你可能感兴趣的:(一个网页抽取的错误(使用lxml.html.document_fromstring))