Python:lxml xpath获得两个不同的类

时间:2015-02-17 13:30:31

标签: python xpath lxml

这是我的示例Python代码

import requests
import lxml.html

page = '<div class="aaaa12"><span class="test">22</span><span class="number">33</span></div><div class="dddd13"><span>Kevin</span></div>' 
tree = lxml.html.fromstring(page)


number = tree.xpath('//span[@class="number"]/text()')
price = tree.xpath('.//div[@class="dddd13"]/span/text()')

print number
print price

当我跑步时,我可以得到如下

['33']
['Kevin']

然而,我想同时得到两个像= ['33','Kevin'] 我试过了

number = tree.xpath('//span[@class="number"]/text() or //div[@class="dddd13"]/span/text()')

我无法获得价值。获得两个不同类的语法是什么?

1 个答案:

答案 0 :(得分:3)

使用| union运算符连接多个完整路径表达式的结果:

number = tree.xpath('//span[@class="number"]/text() | //div[@class="dddd13"]/span/text()')

演示:

>>> import lxml.html
>>> page = '<div class="aaaa12"><span class="test">22</span><span class="number">33</span></div><div class="dddd13"><span>Kevin</span></div>' 
>>> tree = lxml.html.fromstring(page)
>>> tree.xpath('//span[@class="number"]/text() | //div[@class="dddd13"]/span/text()')
['33', 'Kevin']