Python : lxml xpath get two different classes

余生颓废 提交于 2019-12-25 02:54:14

问题


Here is my sample Python code

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

When I ran I could get like below

['33']
['Kevin']

However, I would like to get both at once like = ['33','Kevin'] I tried

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

I couldn't get the value. What is syntax to get two different classes?


回答1:


Use the | union operator to join the results of multiple full path expressions:

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

Demo:

>>> 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']


来源:https://stackoverflow.com/questions/28562717/python-lxml-xpath-get-two-different-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!