简体   繁体   中英

How to get list of childrens of children using xpath?

There is table element which have tr elements in them. While each tr element have td element in it.

<table>
<tr>
<td> some data </td>
<td> other data </td>
</tr>
</table>

I wanted to get the text from the td elements in pairs. But I am willing to do it with xpath.

So, I got the tr element from the lxml tree in one variable by applying xpath. Then applied xpath to get the td elements from that variable. But I get all td elements from table and I wanted to limit td elements from that variable only!

table = parsed.xpath("//table")
trElementFirst = table.xpath("/tr")[0]
tdElementsFromFirstTr = trElementFirst.xpath("/td")

I wanted to get list of td elements for only first tr element. But I get the list of all td elements from table.

tdElementsFromFirstTr = trElementFirst.xpath("//td") grabs all td

import lxml.html as html


htmlStr = '''<table>
<tr>
<td> some data </td>
<td> other data </td>
</tr>

<tr>
<td> NO </td>
<td> OTHER NO </td>
</tr>

</table>'''

parsed = html.fromstring(htmlStr)

table = parsed.xpath("//table")
trElementFirst = table[0].xpath("tr")[0]  
tdElementsFromFirstTr = trElementFirst.xpath("td")

for each in tdElementsFromFirstTr:
    print (each.text)

Output:

some data 
other data 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM