Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over tr's in tbody with Selenium

Set-up

I have a table in my WordPress backend with several rows. Each row contains a link that I want to open using Selenium.

That is, I want to loop over each <tr> in <tbody>.

browser is defined as,

browser = webdriver.Firefox(executable_path='mypath')

The <tbody> has the usual form,

 <tbody>
    <tr>...</tr>
    ...
    <tr>...</tr>
 </tbody>

Code so far

  • Single <tr>

After navigating to the correct page,

tbody = browser.find_element_by_css_selector('.widefat > tbody:nth-child(2)')

browser.find_element_by_xpath('//*[@title="Dutch: Add translation"]').click()

The <tbody> element is correctly selected, and the right link of the first <tr> is correctly opened.

  • Loop over <tr>'s

I don't know how to successfully loop this over all the <tr>'s in the <tbody>.

I have tried the following,

tbody = browser.find_element_by_css_selector('.widefat > tbody:nth-child(2)')

for row in tbody.find_element_by_xpath('./tr'):
    browser.find_element_by_xpath('//*[@title="Dutch: Add translation"]').click()

but this gives TypeError: 'FirefoxWebElement' object is not iterable.

Clearly, tbody.find_element_by_xpath('./tr') is not the correct way of selecting all <tr>'s.

How do I select all <tr>'s correctly?

like image 369
LucSpan Avatar asked Dec 12 '25 08:12

LucSpan


1 Answers

for row in tbody.find_element_by_xpath('./tr') intend to iterate through single WebElement while you need to iterate through the list of elements:

for row in tbody.find_elements_by_xpath('./tr')
like image 196
Andersson Avatar answered Dec 13 '25 23:12

Andersson