简体   繁体   中英

Selenium - Finding xpath by text (td / tr)

I have a large HTML table of emails, i'm trying to find the name of a specific email and then select a button within this element. I can easily find the table body via XPATH with:

//*[@id="reportList"]/tbody

Then within this table there are multiple rows (tr), is it possible to search for text within all table rows?

The closest i've gotten is:

driver.find_element(By.XPATH, '//*[@id="reportList"]/tbody[contains(text(), "example text")]')

Unfortunately this can't locate the element.

html代码

I am aware I can simply copy the XPATH for the specific tr to locate, however for automation purposes i'm trying to pass a string and then search all tr's for my specific text.

As I know table has tr and td , and probably you need td . So the xPath could be like this:

driver.find_element(By.XPATH, "//*[@id='reportList']/tbody//td[contains(text(), 'example text')]")

where ...tbody//td... means that it will search in all subnodes td of tbody . So td should not be a direct child of tbody

PS I would also add wait method to make sure that element is present:

# will wait up to 10 seconds until element will be present on the page
element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//*[@id='reportList']/tbody//td[contains(text(), 'example text')]"))
    )

Note: you have to do some imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Three options to get your xpath:

XPATH= //*[@id='reportList']//*[contains(text(), 'example text')]

If your text is with tr:

XPATH= //*[@id='reportList']/tbody//tr[contains(text(), 'example text')]

If your text with td:

XPATH= //*[@id='reportList']/tbody//tr//td[contains(text(), 'example text')]

I am a newbie to python selenium. I am able to print the text in td using this line

XPATH= //*[@id='reportList']//*[contains(text(), 'example text')]

In my case, I want to loop through rows and click the link in the first column( td ) of the rows( tr ) which has the text 'CREATED' in the 3rd column( td ).

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