如何根据 Selenium 中值的结尾来查找元素?

2024-04-04

我正在处理这样一种情况,每次登录时,报告都会显示在一个表中,该表的 ID 是动态生成的,并带有以“table”结尾的随机文本。

我正在使用 selenium python Web 驱动程序自动化该表。它有语法

driver.find_element_by_xpath('//*[@id="isc_43table"]/tbody/tr[1]/td[11]').click();

帮助我编辑此语法以将其与以 id 结尾的表相匹配"table"。 (仅生成一张表)。


The ends-with https://docs.mendix.com/refguide5/xpath-ends-with XPath 约束函数 https://docs.mendix.com/refguide5/xpath-constraint-functions是其一部分XPath v2.0但根据目前的实施Selenium支持XPath v1.0.

根据HTML您已共享以识别可以使用以下任一元素的元素定位策略 https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890:

  • XPath using contains() https://docs.mendix.com/refguide5/xpath-contains:

    driver.find_element_by_xpath("//*[contains(@id,'table')]/tbody/tr[1]/td[11]").click();
    
  • 此外,正如您所提到的ID动态生成的表所以调用click()在您需要诱导的所需元素上WebDriver等待为了元素可点击您可以使用以下解决方案:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[contains(@id,'table')]/tbody/tr[1]/td[11]"))).click()
    
  • 或者,您也可以使用CSS选择器 as:

    driver.find_element_by_css_selector("[id$='table']>tbody>tr>td:nth-of-type(11)").click();
    
  • 同样,您还可以使用CSS选择器诱导WebDriver等待 as:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[id$='table']>tbody>tr>td:nth-of-type(11)"))).click()     
    

Note:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何根据 Selenium 中值的结尾来查找元素? 的相关文章

随机推荐