fuhrerguxez fuhrerguxez - 7 days ago 7
Python Question

Python xpath - Get text from two different childs in a single operation

I have this block of html (This is not the whole html):

<div class="self-clear">
<div class="item-wrap self-clear float-left">
<h2>
Doran's Start
<span class="notes tooltip"></span>
</h2>
<div class="self-clear item-group">
<div class="main-items float-left ">
<a href="/league-of-legends/item/dorans-ring-25">
<div class="item ajax-tooltip {t:'Item',i:'25'}">
<div class="item-title">
<span class="ajax-tooltip {t:'Item',i:'25'}">Doran's Ring</span>
<br>
</div>
</a>
</div>


and I want to get the text inside
<h2>
and inside each
<div>
in the same operation; I tried doing it like:

for build_names in guide_page.xpath(".//div[@class='self-clear mb10']/div/div[2]/div/h2/text() and "
".//div[@class='self-clear mb10']/div/div[2]/div/div/div/a/div[2]"
"/text()"):


But well, that was not correct... Is it possible to do that?

I need some things out of that operation above but when I do it as two different loops I get an output like:

String from the first for loop
String from the first for loop

String from the second for loop... etc, etc.


I'd like it to be:

String from the first loop
String from the second loop
String from the first loop
String from the second loop and so on


If I didn't explain myself too clear please let me know, thanks.

Answer

You can use union (|) operator to combine two XPath expressions into one :

query = '''.//div[@class='self-clear mb10']/div/div[2]/div/h2/text() | 
           .//div[@class='self-clear mb10']/div/div[2]/div/div/div/a/div[2]/text()'''
for build_names in guide_page.xpath(query):
    ....
Comments