Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying xpath to result of xpath operation

Can I apply Xpath in a "nested" way? I tried below solution, I was expecting first line to return a single <li> element, from which I could then extract its link by applying 2nd xpath expression. However I seem to do something wrong, the 2nd line still returns first a found globally, not in my <li>.

aaa = response.xpath('//ul/li[@class="navitem")]')
bbb = aaa.xpath('//a/@href').extract() 
like image 335
Turo Avatar asked Dec 27 '25 18:12

Turo


1 Answers

You could use:

aaa = response.xpath('//ul/li[@class="navitem")]')
bbb = aaa[0].xpath('.//a/@href').extract()

Note the period . in the 2nd XPath. This will select the @href attribute of all anchor elements that are descendants of the li elements with class="navitem". Without the period ., the expression aaa[0].xpath('//a/@href').extract() will return the @href attribute from all anchor tags in the entire document.

like image 70
gtlambert Avatar answered Dec 30 '25 07:12

gtlambert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!