by.cssContainingText in Python/Selenium

2019-05-10 07:28发布

In Protractor there is a handy by.cssContainingText location strategy that would basically do two things - locate an element (or elements) by a CSS selector and check the element's text to contain a desired string. Sample:

var elm = element(by.cssContainingText('#myid .myclass', 'Some Text'));
expect(elm.isDisplayed()).toBe(true);

How can this be done in Python/Selenium?

Note that I am aware of the XPath way of checking the text. I'm interested specifically in using CSS selectors and checking the text of an element.

1条回答
smile是对你的礼貌
2楼-- · 2019-05-10 08:13

If we look at the by.cssContainingText implementation, we can see that, first, it locates all elements by the CSS selector and then checks the text of the matched elements to contain the desired string.

We can mimic the same logic in Python to create our own custom locator:

def by_css_containing_text(driver, selector, text):
    elements = driver.find_elements_by_css_selector(selector)
    return [element for element in elements 
            if text in (element.text or 
                        element.get_attribute("textContent") or 
                        element.get_attribute("innerText"))]

# usage
driver = webdriver.Firefox()
driver.get(url)

elements = by_css_containing_text(driver, '#myid .myclass', 'Some Text')
self.assertTrue(elements)
self.assertTrue(elements[0].is_displayed())

This is though not the exact same idea as in Protractor since we are not using querySelectorAll directly but making a CSS selector search through the Python/Selenium "find" function.

I'm also not sure if we have to check the textContent and the innerText attribute values - I feel like checking the "text" only would be sufficient enough in practice.

查看更多
登录 后发表回答