I have a LogOut button in a page. I am trying to automate it in Selenium.Following is the source code for that element.
<a class="_2k0gmP" data-reactid="53" href="#">Log Out</a>
This is the code that i am using
driver.findElement(By.cssSelector("._2k0gmP[text='Log Out']"));
But i am repeatedly getting No Such Elemet found exception and sometimes Invalid Selector Exception. Could somebody please help me with this ?
You are getting InvalidSelectorException
because you can't use cssSelector
to find element based on it's inner HTML text. For that you could use xpath or linkText selectors.
xpath: driver.findElement(By.xpath(".//a[text()='Log Out']");
linkText: driver.findElement(By.linkText("Log Out"));
NoSuchElement
exception was probably thrown because you left out _
in class selector as @gecki said so your selector was searching for class which doesn't exist.
Do not leave out the underscore:
driver.findElement(By.cssSelector("._2k0gmP[text='Log Out']"));
However, in this case I would prefer
driver.findElement(By.linkText("Log Out"));
xpath:
driver.findElement(By.xpath("//a[text()='Log Out']");