我有一个表,其中包含多个具有相同LinkText
的链接,因此当我使用它时,总是选择第一个元素,因此不起作用:
driver.find_element_by_partial_link_text('Click here').click()
然后我使用 I javascript 函数通过其 XPath 获取table/tbody
中的所有元素。它可以工作,如果我用变量打印每个元素rows
它看起来像这样<selenium.webdriver...element="...")>
.
在我当前的代码下面:
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")>
如何对找到的每个元素进行click()
?
像这样:
对于行中的 R: 打印 r.click(( # 这不起作用
感谢您的任何帮助。
使用索引进入该行,因为每次单击表中的链接时都会刷新元素索引。如果您不使用索引并尝试使用循环单击链接,则最终可能会获得StaleElementException。
下面是应该有效的逻辑。
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()