What are CSS text selectors?
So I use xpath locators and slowly convert to CSS.
I haven't found a way to do an exact match based on text.
For example converting //a[text()='Log Out'].
I know you can do css=a:contains('Log Out') but I want to match exactly to the text. Also I know I can do link=Log Out but looking for a solution with CSS.
As per the following discussions:
- CSS text selector :contains doesn't work with Selenium
- css pseudo-class :contains() no longer allows anchors
- The :contains pseudo-class isn't in the CSS Spec and is not supported by either Firefox or Chrome (even outside WebDriver).
Python based solution To locate the element with text as Log Out you can use either of the following Locator Strategies:
Using link_text:
element = driver.find_element(By.LINK_TEXT, "Log Out")
Using xpath:
element = driver.find_element(By.XPATH, "//a[text()='Log Out']")
Ideally, to locate the element you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:
Using LINK_TEXT:
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.LINK_TEXT, "Log Out")))
Using XPATH:
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[text()='Log Out']")))
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 Java based solution
- To identify the element with text as Log Out you can use either of the following Locator Strategies:
linkText:
<a href="https://www.janbasktraining.com/blog/selenium-commands-on-comples-webelements/"><a href="https://www.janbasktraining.com/blog/webelement-in-selenium/">WebElement</a></a> element = driver.findElement(By.linkText("Log Out"));
xpath:
WebElement element = driver.findElement(By.xpath("//a[text()='Log Out']"));
Ideally, to identify the element you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:
linkText:
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Log Out")));
xpath:
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[text()='Log Out']")));
References
You can find a couple of relevant detailed discussions in:
selenium.common.exceptions.InvalidSelectorException with “span:contains('string')”