如何根据元素的值以硒结尾查找元素? [英] How to find element based on what its value ends with in Selenium?

查看:112
本文介绍了如何根据元素的值以硒结尾查找元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理这样一种情况:每次登录时,报表都会显示在一个表中,该表的ID是动态生成的,其随机文本以"table"结尾.

I am dealing with a situation where every time I login a report is displayed in a table whose ID is dynamically generated with random text ending with "table".

我正在使用Selenium python Web驱动程序自动化此表.它具有语法

I am automating this table with selenium python web driver. It has Syntax

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

帮我编辑此语法,以使其与以"table"结尾的表匹配. (仅生成一张表).

help me editing this syntax to match it with table ending id with "table". (only one table is generated).

推荐答案

XPath约束功能 XPath v2的一部分.0 ,但按照当前的实现, Selenium 支持 XPath v1.0 .

The ends-with XPath Constraint Function is part of XPath v2.0 but as per the current implementation Selenium supports XPath v1.0.

根据您共享的 HTML ,您可以使用

As per the HTML you have shared to identify the element you can use either of the Locator Strategies:

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

  • 此外,正如您提到的那样,表是动态生成的表,因此要在所需元素上调用click(),您需要为 WebDriverWait 可点击的元素,您可以使用以下解决方案:

  • Further, as you have mentioned that table whose ID is dynamically generated so to invoke click() on the desired element you need to induce WebDriverWait for the element to be clickable and you can use the following solution:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[contains(@id,'table')]/tbody/tr[1]/td[11]"))).click()
    

  • 或者,您也可以将 CssSelector 用作:

    driver.find_element_by_css_selector("[id$='table']>tbody>tr>td:nth-of-type(11)").click();
    

  • 同样,您也可以使用 CssSelector 来将 WebDriverWait 诱导为:

  • Again, you can also use CssSelector inducing WebDriverWait as:

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

  • 注意:您必须添加以下导入:

    Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

    这篇关于如何根据元素的值以硒结尾查找元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆