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.
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:
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 theinnerText
attribute values - I feel like checking the "text" only would be sufficient enough in practice.