Home > front end >  How to get the second element by matching text from the first element. In Selenium, Python
How to get the second element by matching text from the first element. In Selenium, Python

Time:05-05

HTML Snippet for reference:

<tr>
</tr>
<tr>
    <td >TITLE</td>
    <td >NAME</td>
</tr>
<tr>
</tr>

There are a series of tr elements whose position changes, so I have to find the specific one from text within the td sub-elements. I'm trying to grab the second td element with the NAME information by matching the text from the first td element but I don't know how to access it.

I am new to Selenium and just getting into using xpaths to locate elements.

These return the first element just fine:

n = driver.find_element_by_xpath("//*[@id='divDistrictContacts']/table/tbody//tr//*[text()='TITLE]")

n = driver.find_element_by_xpath("//*[@id='divDistrictContacts']/table/tbody//tr/td[text()='TITLE]")

but I don't know where to go from here. I've tried looking it up but can't seem to find how to grab the second element specifically from matching text from the first element.

I've tried adding [position() = 2] and [2] in variations after [text()='TITLE'] and changing the // and * in the xpath, and I either get "no such element" or invalid xpaths.

If this is at all helpful, this is the full xpath (I replaced the tr index with i since it is an unreliable value):

/html/body/div[1]/div[2]/div[5]/table/tbody/tr[i]/td[2]

CodePudding user response:

You can nested one [ ] inside another [ ]

Maybe first use TITLE to get tr - //tr[td[text()="TITLE"]]

And later get second td in this tr - (//tr[td[text()="TITLE"]]//td)[2]


EDIT:

You can also use following-sibling

//td[text()="TITLE"]/following-sibling::td

Full working example:

from selenium import webdriver
from selenium.webdriver.common.by import By
#from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager

#driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

html = '''<!DOCTYPE html>
<html>
<body>
<table>
<tr></tr>
<tr>
    <td >TITLE</td>
    <td >NAME</td>
</tr>
<tr></tr>
</table>
</body>
</html>
'''

driver.get("data:text/html;charset=utf-8,"   html)

item = driver.find_element(By.XPATH, '(//tr[td[text()="TITLE"]]//td)[2]')
print(item.text)

item = driver.find_element(By.XPATH, '//td[text()="TITLE"]/following-sibling::td')
print(item.text)

CodePudding user response:

You are looking for following-sibling

//td[text()='TITLE']//following-sibling::td

enter image description here

  • Related