Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, lxml retrieving all elements in a list

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()')
like image 989
user7466620 Avatar asked Aug 09 '26 14:08

user7466620


1 Answers

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 
like image 117
unutbu Avatar answered Aug 12 '26 04:08

unutbu