0

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

4

2 回答 2

2
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)
于 2013-03-15T12:58:39.543 回答
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>
于 2013-03-15T12:55:55.370 回答