I'm attempting to get all elements in a list from a website
From the following html snippet:
<ul>
<li class="name"> James </li>
<li> Male </li>
<li> 5'8" </li>
</ul>
My current code takes uses the xpath of and stores the names in a list. Is there a way to get all three fields as a list?
My code:
name = tree.xpath('//li[@class="name"]/text()')
import lxml.html as LH
tree = LH.parse('data')
print(tree.xpath('//li[../li[@class="name" and position()=1]]/text()'))
prints
[' James ', ' Male ', ' 5\'8" ']
The XPath '//li[../li[@class="name" and position()=1]]/text()' means
//li # all li elements
[ # whose
.. # parent
/ # has a child
li # li element
[ # whose
@class="name" # class attribute equals "name"
and # and
position()=1] # which is the first child element
]
/text() # return the text of those elements
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