XPath and html: merge tr-pairs ? (or text() thereof)

Viewed 28

Is this possible? I have a list of <tr> elements and the XPath expression //tr. Instead of returning/matching each <tr> element individually, I want to merge the first with the second, the third with the fourth, etc. Is this possible?

I'm using the lxml.html python package for html parsing and xpath evaluation.

2 Answers

I managed to get it working for text concat():

import lxml.etree as ET
import elementpath

doc = ET.HTML("<tr><td>1</td></tr><tr><td>2</td></tr><tr><td>3</td></tr><tr><td>4</td></tr>")

for item in elementpath.select(doc, "//tr[position() mod 2 = 1]/concat(.,' => ',following-sibling::tr[1])"):
    print(item)

Output:

1 => 2
3 => 4

Still looking for a solution that merges two <td>'s into a single <tr> and returns an array of those <tr>'s with half the original length.

You can get two lists (odd and even) of elements with XPath expressions:

//tr[position() mod 2=1] # returns 1st, 3rd, 5th... tr node
//tr[position() mod 2=0] # returns 2nd, 4th...

and then (let say we got two lists of strings: even and odd) join each pair with Python code

for i, j in zip(even, odd):
    print(' '.join([i, j]))

This should return joined with space tr values of 1 + 2, 3 + 4, 5 + 6...

Related