Unable to find the locator with Link Text test case getting failed - selenium

I am not able find the locator with anchor tag. Using xpath doesn't give the result.
Here is the HTML code :
<a id="sme1" class="item" href="/website-url" onclick="swapClasses('sme1')"
target="main" style="background-color:
transparent;">Mailboxes</a>
Selenium code :
private static final String baseURL = "http://10.112.75.248/";
private static final String adminURL = baseURL + "manager/";
private static String username = "admin";
private static String password = "default";
WebDriver driver ;
SearchElement searchEl;
#BeforeTest
public void setBaseURL(){
driver = new FirefoxDriver();
driver.get(adminURL);
searchEl = new SearchElement();
}
#Test(priority=0)
public void verifyLoginSuccessFull() {
searchEl.getElementsByXpath(driver, "//input[#name='username']").sendKeys(username);
searchEl.getElementsByXpath(driver, "//input[#name='password']").sendKeys(password);
searchEl.getElementsByXpath(driver, "//input[#name='submit']").submit();
String expected = "Selenium Home Page";
Assert.assertEquals(driver.getTitle(), expected);
}
#Test(priority=1)
public void addMailbox(){
//WebDriverWait wait = new WebDriverWait(driver, 1000);
//wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='Mailboxes']")));
//driver.findElement(By.id("smel")).click();
searchEl.getElementsByLinkText(driver, "//a[text()='Mailboxes']").click(); //This line of code not fetching the locator.
}
SearchElement class used as a controller :
public class SearchElement {
public WebElement getElementsByXpath(WebDriver driver,String locator){
WebElement el = driver.findElement(By.xpath(locator));
return el;
}
public WebElement getElementsByLinkText(WebDriver driver,String locator){
WebElement el = driver.findElement(By.linkText(locator));
return el;
}
}
Actual Error :
Unable to locate element: {"method":"link
text","selector":"//a[text()='Mailboxes']"}
Note : The URL is different when the user logs in and when the user is presented the login page. I dont know it might be a problem.
Please help in advance.

By.linkText() method expects link text as parameter, but in that code you're passing XPath string. Try to pass the link text instead :
searchEl.getElementsByLinkText(driver, "Mailboxes").click();

try this.
//a[.='Mailboxes']
This is a text base search and "." inside the xpath navigates you to the parent

Related

The button in date picker is getting clicked more than the number of clicks needed [duplicate]

I am trying to select a "Depart date" as of 31st october 2018 from the calender https://spicejet.com/ But I am getting error "unknown error: Element is not clickable at point (832, 242). Other element would receive the click: ..." Please help me out. Here is my code getting such exception:
public class bookflight extends Thread {
UtilityMethods utilObj= new UtilityMethods();
#Test
public void SighnUp() throws IOException
{
utilObj.getdriver().get("https://spicejet.com");
utilObj.getdriver().manage().window().maximize();
utilObj.getdriver().findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
utilObj.getdriver().findElement(By.xpath("//a[contains(text(),'Guwahati (GAU)')]")).click();
utilObj.getdriver().findElement(By.xpath("//a[contains(text(),'Goa (GOI)')]")).click();
utilObj.getdriver().findElement(By.className("ui-datepicker-trigger")).click();
utilObj.getdriver().findElement(By.xpath("//div[#class='ui-datepicker-group ui-datepicker-group-first'])/parent:://table[#class='ui-datepicker-calendar']following-sibling::./a/contains(text(),'31')")).click();
}
}
To select From (e.g. Guwahati(GAU)), To (e.g. Goa(GOI)) destination and DEPART DATE as 31/10 within the url https://spicejet.com/ you need to induce WebDriverWait for the desired element to be clickable and you can use the following solution:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class spicejet_login {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://spicejet.com");
new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#id='ctl00_mainContent_ddl_originStation1_CTXT']"))).click();
driver.findElement(By.xpath("//div[#id='glsctl00_mainContent_ddl_originStation1_CTNR']//table[#id='citydropdown']//li/a[#value='GAU']")).click();
driver.findElement(By.xpath("//div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//table[#id='citydropdown']//li/a[#value='GOI']")).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//table[#class='ui-datepicker-calendar']//tr//a[contains(#class,'ui-state-default') and contains(.,'31')]"))).click();
}
}
Browser Snapshot:
There is lots of different factors which results into this exception,
i like to suggest you to try putting some wait.
WebDriverWait wait = new WebDriverWait(utilObj.getdriver(), 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("ctl00_mainContent_ddl_originStation1_CTXT")));
then try clicking element,
utilObj.getdriver().findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
You can click on element by Action class, based on Exception type:
Actions action = new Actions(driver);
action.moveToElement(WebElement to click).click().perform();
Updated answer to click next date.
//div[contains(#class, 'ui-datepicker-group-first')]//td[#data-month='9' and #data-year='2018']/a[.=31]
You can modify the above XPATH to select date based on YEAR/MONTH/DATE. for more XPath creation go-through my answers.
var path ="//div[contains(#class, 'ui-datepicker-group-first')]//td[#data-month='9' and #data-year='2018']/a[.=31]";
var elem = document.evaluate(path, window.document, null, 9, null ).singleNodeValue;
console.log( elem );
elem.click();
When you enter FROM and TO data, then DEPART DATE field get auto selected. So, just you need to select the first data using javascript.
FROM « //div[#id='ctl00_mainContent_ddl_originStation1_CTNR']//a[#text='Guwahati (GAU)']
TO « //div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[#text='Goa (GOI)']
DEPART DATE «
//div[contains(#class, 'ui-datepicker-group-first')]//a[contains(#class, 'ui-state-active')]
sample test program.
import io.github.yash777.driver.Browser;
import io.github.yash777.driver.Drivers;
import io.github.yash777.driver.WebDriverException;
public class SpiceJET {
static WebDriver driver;
static WebDriverWait explicitWait;
public static void main(String[] args) throws WebDriverException, IOException {
test();
}
public static void test() throws WebDriverException, IOException {
Drivers drivers = new Drivers();
String driverPath = drivers.getDriverPath(Browser.CHROME, 63, "");
System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
driver = new ChromeDriver( capabilities );
explicitWait = new WebDriverWait(driver, 10);
//Maximize browser window
driver.manage().window().maximize();
//Go to URL which you want to navigate
driver.get("https://spicejet.com/");
clickElement("//input[#id='ctl00_mainContent_ddl_originStation1_CTXT'][1]");
clickElement("//div[#id='ctl00_mainContent_ddl_originStation1_CTNR']//a[#text='Guwahati (GAU)']");
clickElement("//input[#id='ctl00_mainContent_ddl_destinationStation1_CTXT'][1]");
clickElement("//div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[#text='Goa (GOI)']");
clickUsingJavaScript("//div[contains(#class, 'ui-datepicker-group-first')]//a[contains(#class, 'ui-state-active')]");
}
}
public static void clickElement(String locator) {
By findBy = By.xpath( locator );
WebElement element = explicitWait.until(ExpectedConditions.elementToBeClickable( findBy ));
element.click();
}
public static void clickUsingJavaScript( String locator ) {
StringBuffer click = new StringBuffer();
click.append("var elem = document.evaluate(\""+locator+"\", window.document, null, 9, null ).singleNodeValue;");
click.append("elem.click();");
System.out.println("JavaScript Click.");
jse.executeScript( click.toString() );
}
For Automatic management of Selenium Driver Executable’s in run-time for Java use SeleniumWebDrivers
NOTE: If you are selecting DEPART DATE which got auto selected then selenium throws exception
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error:
Element <input type="text" readonly="readonly" id="ctl00_mainContent_view_date2" class="custom_date_pic required home-date-pick">
is not clickable at point (784, 241). Other element would receive the click: <span class="ui-datepicker-month">...</span>
I hope below code is helpful and handle departure and return date
public class SpicejetDropdowns1 {
public static void main(String[] args) throws InterruptedException
{ System.setProperty("webdriver.chrome.driver","E:\\ChromeDriver\\ChromeDriver2.46\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.spicejet.com/");
driver.manage().window().maximize();
System.out.println(driver.getTitle()); driver.findElement(By.cssSelector("#ctl00_mainContent_rbtnl_Trip_1")).click();
// OriginStation
driver.findElement(By.xpath(".//*[#id='ctl00_mainContent_ddl_originStation1_CTXT']")).click();
driver.findElement(By.cssSelector("a[value='DEL']")).click();
// Destination
driver.findElement(By.xpath(".//*[#id='ctl00_mainContent_ddl_destinationStation1_CTXT']")).click();
driver.findElement(By.xpath("(//a[#value='HYD'])[2]")).click();
Thread.sleep(3000); driver.findElement(By.xpath("//input[#id='ctl00_mainContent_view_date1']")).click();
if(driver.findElement(By.id("Div1")).getAttribute("style").contains("1"))
{
System.out.println("its enabled");
Assert.assertTrue(true);
}
else
{
Assert.assertTrue(false);
}
while(!driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText().contains("October"))
{
// driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click();
driver.findElement(By.xpath("//a[#class='ui-datepicker-next ui-corner-all']/span[#class='ui-icon ui-icon-circle-triangle-e']")).click();
System.out.println(driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText());
}
List<WebElement> dates= driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td"));
int count= dates.size();
for(int i=0; i<count; i++)
{
String txt = driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).getText();
if(txt.equalsIgnoreCase("28"))
{
driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).click();
System.out.println(txt);
break;
}
}
// Return Date Selection
Thread.sleep(3000); driver.findElement(By.xpath("//input[#id='ctl00_mainContent_view_date2']")).click();
while(!driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText().contains("October"))
{
// driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click();
driver.findElement(By.xpath("//a[#class='ui-datepicker-next ui-corner-all']/span[#class='ui-icon ui-icon-circle-triangle-e']")).click();
System.out.println(driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText());
}
List<WebElement> MDates= driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td"));
int Mcount= dates.size();
for(int i=0; i<Mcount; i++)
{
String txt = driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).getText();
if(txt.equalsIgnoreCase("31"))
{
driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).click();
System.out.println(txt);
break;
}
}
//Select Passengers
Thread.sleep(4000);
driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).click();
Thread.sleep(4000);
WebElement Adults = driver.findElement(By.xpath("//select[#id='ctl00_mainContent_ddl_Adult']")); Select adultsdrp = new Select(Adults);
adultsdrp.selectByValue("2");
WebElement childs = driver.findElement(By.xpath("//select[#id='ctl00_mainContent_ddl_Child']"));
Select childsdrp = new Select(childs);
childsdrp.selectByValue("2");
driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).click();
System.out.println(driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).getText());
//Static Currency Dropdown
WebElement Currency = driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency"));
Select currencydrp = new Select(Currency);
currencydrp.selectByValue("USD"); Assert.assertEquals(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")).getAttribute("value"), "USD"); System.out.println(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")).getAttribute("value"));
}
}

driver.getCurrentUrl() returns data:, instead of actual URL

I'm writing a test with Serenity BDD-Cucumber.
I want to check if the URL is correct when it's navigated. But the result always shows data, and my test fails with driver.getCurrentUrl().
Please see my code below:
Feature steps:
public void homePageOpens() {
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains("STORE"));
String homepageUrl = navigationUser.getUrl();
System.out.println(homepageUrl);
Assert.assertTrue(homepageUrl.contains("https://www.example.com/index.html"));
driver.close();
}
Navigation steps:
#Step("Get the URL")
public String getUrl() { return basePage.getUrl();
}
BasePage:
public String getUrl() {
System.out.println("just testing");
WebDriver driver = new ChromeDriver();
return driver.getCurrentUrl();
}
This also opens a page with URL: "data:," which doesn't close after the test
Use driver.get in order to navigate somewhere.
String someUrl = "https://www.example.com/index.html";
driver.get(someUrl);
This code:
public String getUrl() {
System.out.println("just testing");
WebDriver driver = new ChromeDriver();
return driver.getCurrentUrl();
}
just launch the browser, and the initial url is data:,.
Also it's unclear why BasePage getUrl() method launches the new webdriver and uses it as a local variable. But in homePageOpens() method in feature steps looks like some another driver used..

How can I verifying a footer text using selenium Junit

I want to verify a text in the footer. I normally copied the XPath locator and find element then get the text of the element, but nothing happens for this code part in Junit.
From this website I need to get the footer text:
https://www.qaagility.com/
Here is the code I am using for this. I know there is another way of doing it.
public class QAA_mock3 {
private WebDriver driver;
private Map<String, Object> vars;
JavascriptExecutor js;
#Before
public void setUp() {
driver = utils.HelperFunctions.createAppropriateDriver("Chrome");
js = (JavascriptExecutor) driver;
vars = new HashMap<String, Object>();
}
#Test
public void test() {
String ExpTitle = "QAAgility" ;
Actions actions = new Actions(driver);
By TwitterLink = By.xpath("//*[#id=\"custom_html-4\"]/div/div[1]/a[2]");
By footer = By.xpath("//div[#id='footer']");
By imglogo = By.cssSelector("img.header-image");
driver.get(" https://www.qaagility.com");
System.out.println("Loaded page...");
String ActTitle = driver.getTitle();
System.out.println("page Title..."+ ActTitle);
if(ActTitle.contains(ExpTitle)) {
System.out.println("Verified the title for ..."+ ExpTitle);
}
else
System.out.println("Title verification went wrong...");
WebElement imgSize = driver.findElement(imglogo);
Dimension imageSize = imgSize.getSize();
int Height = imageSize.getHeight();
int Width = imageSize.getWidth();
System.out.println("The size of the Logo is : Width = "+ Width + "; Height = "+Height);
WebElement Twitter = driver.findElement(TwitterLink);
String Href = Twitter.getAttribute("href");
System.out.println("Twitter Link is :"+ Href);
WebElement footerText = driver.findElement(footer);
System.out.println("WebElement for footer is"+ footerText);
actions.moveToElement(footerText).build().perform();
String FTText = footerText.getText();
System.out.println("Footer Text is :"+ FTText);
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}
You wrong define footer locator:
By footer = By.xpath("//div[#id='footer']");
Try this:
By footer = By.className("copyright-bar")

how to get a screenshot for failure tests with method name of failure test

With the listeners how can we solve it.Give me a better solution.I tried using with Listners but it is not giving the method name of failure test, it giving the screenshot name with current method name.for example if a test is failed in one class i want that class method name only.but it is giving execution method as screen shot name
public class Invoke {
public static WebDriver driver;
public static void invoking() throws Exception {
System.setProperty("webdriver.chrome.driver",
"E:\\AK\\Selenium files\\chromedriver_win32 (1)\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("facebook.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.xpath("akdhd")).click();
}
}
public class Excecution {
#Test public static void m() throws Exception {
Invoke.invoking();
String val=ExcelDynamic.r("C:\\Users\\PC\\Desktop\\facebook.xlsx", "Sheet1", 1, 1);
System.out.println(val);
}
This code is in another class
public static void screen(String Filepath) throws Exception {
TakesScreenshot ts = ((TakesScreenshot) driver);
File fi = ts.getScreenshotAs(OutputType.FILE);
String img = Thread.currentThread().getStackTrace()[2].getMethodName() + ".jpg";
FileUtils.copyFile(fi, new File(Filepath + img));
}
}
i'm calling this method in execution class so it is printing screenshot name m. But i want output name as invoking for screen shot
Below is a utility method that returns the calling method name.
public static String get_calling_method_name() {
return Thread.currentThread().getStackTrace()[2].getMethodName();
}
Hope this solves the issue.
You may try By this,
To change with first index,
String img = Thread.currentThread().getStackTrace()[1].getMethodName() + ".jpg";
Hope it will work.

Selenium xpath getting changed during run time

Scenario - Valid login to www.homeshop18.com and then from the Digital Menu select "Samsung".
The results are displayed and now I need to choose another brand - Micromax from the Brand section (displayed at the left side of the page)
which requires scrolling and selecting Micromax.
Issue:
Though the xpath of Micromax is correct which is //*[#id='filter_1Option_12']//div[#class='ez-checkbox'] but I see during run time of the script - some other brand is getting selected instead of micromax.
Kindly advise.
//Class for valid login to www.homeshop18.com
public class HomeShop_Login_Test
{
#FindBy(xpath="//a[#id='signInHeaderLink']") WebElement SignIn_Link;
#FindBy(xpath=".//input[#id='emailId']") WebElement Email;
#FindBy(xpath=".//input[#id='existing_user_radio']") WebElement Existing_User_Radio;
#FindBy(xpath=".//input[#id='new_user_radio']") WebElement New_User_Radio;
#FindBy(xpath=".//input[#id='password']") WebElement Password;
#FindBy(xpath=".//a[#id='signin']") WebElement SignIn_Button;
#FindBy(xpath="//a[#title='Close']") WebElement Close_Home;
public void Login_Valid()
{
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement SignIn_Link = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[#id='signInHeaderLink']")));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click()", SignIn_Link);
Email.sendKeys("xxx#gmail.com");
boolean selected;
selected = New_User_Radio.isSelected();
if(selected)
{
Existing_User_Radio.click();
}
Password.sendKeys("xxx");
SignIn_Button.click();
}
//Class to choose Samsung from Digital menu
public class Browse_Samsung_Mobile
{
#FindBy(xpath="//*[#id='CategoryMenu1']//a[text()='Digital']") WebElement Digital_Menu;
#FindBy(xpath="//*[#id='CategoryMenu1']//a[#title='Samsung']") WebElement Samsung_SubMenu;
#FindBy(xpath="//*[#id='filter_1Option_19']//span[#class='selected_filter_img']") WebElement Micromax;
public void Browse_Samsung()
{
WebDriverWait wait = new WebDriverWait(driver, 30);
Actions act = new Actions(driver);
act.moveToElement(Digital_Menu).perform();
act.click(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='CategoryMenu1']//a[#title='Samsung']")))).build().perform();
//WebElement Micromax = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id='filter_1Option_12']//span[#class='selected_filter_img']")));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click()", Micromax);
}
}
//class to call above two classes
public class Validate_Browse_Samsung_Mobile
{
WebDriver driver;
#Test
public void Validate_Browse()
{
driver = BrowserFactory.getBrowser("Firefox");
driver.get(DataProviderFactory.getConfig().getURL());
HomeShop_Login_Test login = PageFactory.initElements(driver, HomeShop_Login_Test.class);
login.Login_Valid();
Browse_Samsung_Mobile browse = PageFactory.initElements(driver, Browse_Samsung_Mobile.class);
browse.Browse_Samsung();
}
}
You should try with their name using title attribute as below :-
WebElement micromax = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("a[title ~= "Micromax"] input")));
You should use following XPath to choose proper check-box:
//a[#title="GSM Mobile Phones - Micromax"]/div/input