by.cssContainingText in Python/Selenium by.cssContainingText in Python/Selenium selenium selenium

by.cssContainingText in Python/Selenium


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"))]# usagedriver = 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.