问题
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