Reputation: 2298
I have a table with several links that have the same LinkText
, so when I use this always the first element is selected, so doesn't work:
driver.find_element_by_partial_link_text('Click here').click()
Then I use I javascript function to get all the elements within the table/tbody
using its XPath. It works and if I print each element with the variable rows
it looks
like this <selenium.webdriver...element="...")>
.
Below my current code:
import time
from selenium import webdriver
url="http://example_url.com"
driver_path="/driver/chromedriver"
driver = webdriver.Chrome(driver_path)
driver.get (url)
rows = driver.execute_script('''function getElementByXpath(path) {..};return getElementByXpath("//*[@id='someID']/table/tbody/").rows''')
>>> for r in rows:
... print r # This prints the elements within 'rows'
... #some other code
...
<selenium.webdriver.remote.webelement.WebElement (session="e819b7b267ba043d4233e118c5844e1e", element="0.7287146883212632-2")>
<selenium.webdriver.remote.webelement.WebElement (session="e819b7b267ba043d4233e118c5844e1e", element="0.7287146883212632-3")>
<selenium.webdriver.remote.webelement.WebElement (session="e819b7b267ba043d4233e118c5844e1e", element="0.7287146883212632-4")>
<selenium.webdriver.remote.webelement.WebElement (session="e819b7b267ba043d4233e118c5844e1e", element="0.7287146883212632-5")>
How would be the way to do click()
over each element found?
something like:
for r in rows: print r.click() # This doesn't work
Thanks for any help.
Upvotes: 1
Views: 1468
Reputation: 14135
you have to get to the row using the index, as the element index will be refreshed each time you click on the link in the table. If you don't use the index and try to click on the links using a loop you might end-up getting StaleElementException.
Below is the logic that should work.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
url="http://example_url.com"
driver_path="/driver/chromedriver.exe"
driver = webdriver.Chrome(driver_path)
driver.get (url)
numberOfRows = len(driver.find_elements_by_xpath("//*[@id='someID']/table/tbody//tr"))
for iRow in range(numberOfRows):
# wait until the row is present (you need this when you are coming back to the row containing table
currentRow = WebDriverWait(driver,30).until(EC.presence_of_element_located((By.XPATH,"(//*[@id='someID']/table/tbody//tr)[str(" + (iRow+1) + ")]")))
# if you want to access the link in the row
linkInCurrentRow = currentRow.find_elements_by_xpath(".//a[@attribute='attribute_value']")
# click on the link or you can perform desired operation
linkInCurrentRow.click()
#write the logic below to navigate to the table containing page
driver.back()
Upvotes: 1