python html parser库lxml的介绍和使用

使用由 Python 编写的 lxml 实现高性能 XML 解析 [url]http://blog.csdn.net/yatere/article/details/6667043[/url]

[color=darkblue][size=x-large]用lxml解析HTML[/size][/color][url]http://www.cnblogs.com/descusr/archive/2012/06/20/2557075.html[/url]


分步遍历:比先遍历得到body的某个div,然后在使用这个div的内容做遍历基础,继续通过它往下遍历
def scanningHotArticle(url):
print url
request=requests.get(url)
dom=soupparser.fromstring(request.content)
body=dom[1]
articleList=body.xpath("//div[@class='block untagged mb15 bs2']")
for article in articleList:
articleStr= etree.tostring(article)
articleBody=soupparser.fromstring(articleStr)
print len(articleBody.xpath("//div[@class='detail']"))

结构是body-*->div[class='block untagged mb15 bs2'],这个div下面又存在许多div,然后把这个div当作根节点,在继续xpath查找下面的元素。


[size=x-large][color=red]python html parser库lxml的介绍和使用(快速入门)[/color][/size]
[url]http://blog.csdn.net/marising/article/details/5821090[/url]
lxm是python的一个html/xml解析并建立dom的库,lxml的特点是功能强大,性能也不错,xml包含了ElementTree ,html5lib ,beautfulsoup 等库,但是lxml也有自己相对应的库,所以,导致lxml比较复杂,初次使用者很难了解其关系。

[b]1. 解析html并建立dom[/b]
>>> import lxml.etree as etree

>>> html = '<html><body id="1">abc<div>123</div>def<div>456</div>ghi</body></html>'
>>> dom = etree.fromstring(html)
>>> etree.tostring(dom)
'<html><body id="1">abc<div>123</div>def<div>456</div>ghi</body></html>'



如果用beautifulsoup的解析器,则
>>> import lxml.html.soupparser as soupparser
>>> dom = soupparser.fromstring(html)
>>> etree.tostring(dom)
'<html><body id="1">abc<div>123</div>def<div>456</div>ghi</body></html>'

但是我强烈建议使用soupparser,因为其处理不规范的html的能力比etree强太多。



[b]2. 按照Dom访问Element[/b]
[b]子元素长度[/b]
>>> len(dom)
1


[b]访问子元素:[/b]
>>> dom[0].tag
'body'


[b]循环访问:[/b]
>>> for child in dom:
... print child.tag
...
body


[b]查看节点索引[/b]
>>>body = dom[0]
>>> dom.index(body)
0


[b]字节点获取父节点[/b]
>>> body.getparent().tag
'html'


[b]访问所有子节点[/b]
>>> for ele in dom.iter():
... print ele.tag
...
html
body
div
div

[b]遍历和打印所有子节点:[/b]
>>> children = list(root)
>>> for child in root:
... print(child.tag)


[b]元素的兄弟或邻居节点是通过next和previous属性来访问的[/b]
The siblings (or neighbours) of an element are accessed as next and previous elements:
>>> root[0] is root[1].getprevious() # lxml.etree only! 
True
>>> root[1] is root[0].getnext() # lxml.etree only!
True


[b]3. 访问节点属性[/b]
>>> body.get('id')
'1'

也可以这样
>>> attrs = body.attrib
>>> attrs.get('id')
'1'


[b]带属性的元素[/b]
XML元素支持属性,可以用Element工厂方法直接创建。
>>> root = etree.Element("root", interesting="totally")
>>> etree.tostring(root)
b’<root interesting="totally"/>’


[b]可以使用set和get方法访问这些属性[/b]:
>>> print root.get("interesting")
totally
>>> root.set("interesting", "somewhat")
>>> print root.get("interesting")
somewhat


也可以使用attrib性质的字典接口
>>> attributes = root.attrib
>>> print(attributes["interesting"])
somewhat
>>> print(attributes.get("hello"))
None
>>> attributes["hello"] = "Guten Tag"
>>> print(attributes.get("hello"))
Guten Tag
>>> print(root.get("hello"))
Guten Tag



[b]4. 访问Element的内容[/b]
>>> body.text
'abc'
>>> body.tail

text只是从本节点开始到第一个字节点结束;tail是从最后一个字节结束到本节点未知。

[b]访问本节点所有文本信息[/b]
>>> body.xpath('text()')
['abc', 'def', 'ghi']



[b]访问本节点和子节点所有文本信息[/b]
>>> body.xpath('//text()')
['abc', '123', 'def', '456', 'ghi']


貌似返回本文档中所有文字信息
body.text_content()返回本节点所有文本信息。

[b]5.Xpath的支持[/b]
所有的div元素
>>> for ele in dom.xpath('//div'):
... print ele.tag
...
div
div

[b]
id=“1”的元素[/b]
>>> dom.xpath('//*[@id="1"]')[0].tag
'body'



[b]body下的第1个div[/b]
>>> dom.xpath('body/div[1]')[0].tag
'div'



参考:
lxml的官方文档:[url]http://codespeak.net/lxml/[/url]
HtmlParser的性能:[url]http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值