lxml findall div和span标签

时间:2013-03-15 12:41:21

标签: python html-parsing lxml

如何找到保留顺序的所有div和span标签。使用BeautifulSoup非常简单:soup.findAll(name=['span', 'div']),但我最近切换到lxml,因为它比BeautifulSoup快得多。

2 个答案:

答案 0 :(得分:1)

import lxml.html as LH
content = '''\
<tr>
<div>idend</div>
<span>Green<\span>
<tr>
'''
root = LH.fromstring(content)
for tag in root.xpath('//*[self::div or self::span]'):
    print(tag)

产量

<Element div at 0xb751f23c>
<Element span at 0xb751f11c>

答案 1 :(得分:1)

import lxml.html
from lxml.cssselect import CSSSelector
content = result.read()
page_html = lxml.html.fromstring(content)

elements = page_html.xpath('//*[self::div or self::span]')

sd_selector = CSSSelector('span,div')
elements = sd_selector(page_html)