首页 文章

如何在Selenium Webdriver(Python)中找到包含特定文本的元素?

提问于
浏览
161

我正在尝试使用Selenium测试复杂的javascript界面(使用Python界面,并跨多个浏览器) . 我有许多形式的按钮:

<div>My Button</div>

我希望能够搜索基于“我的按钮”的按钮(或非区分大小写的部分匹配,例如“我的按钮”或“按钮”)

我发现这非常困难,在某种程度上我觉得我错过了一些明显的东西 . 我到目前为止最好的事情是:

driver.find_elements_by_xpath('//div[contains(text(), "' + text + '")]')

但是,这是区分大小写的 . 我尝试过的另一件事是遍历页面上的所有div,并检查element.text属性 . 但是,每次你得到表格的情况:

<div class="outer"><div class="inner">My Button</div></div>

div.outer也有“我的按钮”作为文本 . 为了解决这个问题,我试图查看div.outer是否是div.inner的父级,但是无法弄清楚如何做到这一点(element.get_element_by_xpath('..')返回一个元素的父级,但它测试不等于div.outer) . 此外,迭代遍历页面上的所有元素似乎非常慢,至少使用Chrome webdriver .

想法?

编辑:这个问题有点模糊 . 在这里询问(并回答)更具体的版本:How to get text of an element in Selenium WebDriver (via the Python api) without including child element text?

6 回答

  • 211
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(), 'YourTextHere')]")));
        assertNotNull(driver.findElement(By.xpath("//*[contains(text(), 'YourTextHere')]")));
        String yourButtonName=driver.findElement(By.xpath("//*[contains(text(), 'YourTextHere')]")).getAttribute("innerText");
        assertTrue(yourButtonName.equalsIgnoreCase("YourTextHere"));
    
  • 0

    试试这个 . 很容易:

    driver.getPageSource().contains("text to search");
    

    这在selenium web驱动程序中真的对我有用 .

  • 2

    你可以尝试像xpath一样:

    '//div[contains(text(), "{0}") and @class="inner"]'.format(text)
    
  • -16

    请尝试以下方法:

    driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
    
  • 8

    您也可以将它与页面对象模式一起使用,例如:

    试试这段代码:

    @FindBy(xpath = "//*[contains(text(), 'Best Choice')]")
    WebElement buttonBestChoice;
    
  • 21

    对文本的 case insensitive search 使用driver.find_elements_by_xpathmatches正则表达式匹配函数 .

    driver.find_elements_by_xpath("//*[matches(.,'My Button', 'i')]")
    

相关问题