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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With