Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python / Selenium - using a conditional in an xpath

I need to find a particular element in some webpages which are basically identical in structure, using the following xpath:

//*[@id="detailPCTtableHeader"]/tbody/tr[10]/td[2]/div/span/span[1]/text()

The problem is that in some pages tr[10] is tr[11].

Is there a way to tell Selenium to search for tr[10] or tr[11]?

like image 467
Marc Adler Avatar asked Dec 06 '25 07:12

Marc Adler


2 Answers

You could use the position() to evaluate the index:

element = driver.find_element_by_xpath("id('detailPCTtableHeader')/tbody/tr[position()=10 or position()=11]/td[2]/div/span/span[1]")
like image 136
Florent B. Avatar answered Dec 08 '25 21:12

Florent B.


"Is there a way to tell Selenium to search for tr[10] or tr[11]?"

Use position() :

tr[position() = 10 or position() = 11]

Alternatively, if only one of tr[10] and tr[11] ever exists at a time, meaning it is always the last tr, you can simply use last() :

tr[last()]
like image 41
har07 Avatar answered Dec 08 '25 19:12

har07