You can visit on makemytrip.com. Hover on "trips" and click on "cancel bookings".
Here is the code what I am trying to execute and don't know where am I going wrong.
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
".\\exeFile\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.navigate().to("https://www.makemytrip.com/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
List<WebElement> dd_values=driver.findElements(By.xpath("//li[#class='menu-
trigger']//ul[#class='ch__profileOverlayTabs ch__capitalize
append_bottom20']//li"));
for (WebElement elements: dd_values) {
System.out.println("values of each attribute :
"+elements.getAttribute("innerHTML"));
if (elements.getAttribute("innerHTML").contains("Cancel Bookings")) {
elements.click();
break;
}
You have to perform the mouse hover action using Actions class and then need to perform the required action as below
Working Code:
driver.get("https://www.makemytrip.com/");
driver.manage().window().maximize();
//Explicit wait is added after the Page load
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("Make"));
WebElement element=driver.findElement(By.xpath("//div[#class='ch__userInteraction ch__clearfix']//span[text()='trips']"));
Actions builder=new Actions(driver);
builder.moveToElement(element).build().perform();
driver.findElement(By.xpath("//div[#class='my_trips log-in-trip ch_trip_logged header-dropdown']//a[text()='Cancel Bookings']")).click();
Below is the code :
package com.demo.core;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.HasInputDevices;
import org.openqa.selenium.interactions.Mouse;
import org.openqa.selenium.interactions.internal.Locatable;
public class MakeMyTripDemo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "J:\\STADIUM\\selenium-demo\\src\\main\\resources\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.navigate().to("https://www.makemytrip.com/");
WebElement trips = driver.findElement(By.xpath("//a[#mt-class='trips_icon']"));
mouseOverElement(driver, trips);
WebElement cancelBooking = driver.findElement(By.xpath("//a[#id='ch_trips_cancel']"));
jsPress(driver, cancelBooking);
}
private static void mouseOverElement(WebDriver driver, WebElement webElement) {
Mouse mouse = ((HasInputDevices) driver).getMouse();
mouse.mouseMove(((Locatable) webElement).getCoordinates());
}
public static void jsPress(WebDriver driver, WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
}
}
Hope it helps you. It is working.
Related
I have send a searchable keyword through send keys in search text field of youtube. But when the drop down emerge below search textfield, I am unable to store the dropdown items in List and click anyone of them. I am getting '0' as a result in printing list size.
package SomeBasicAutomationPractice;
import java.util.List;
import org.apache.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Practice_dynamic_xpath {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "G:\\VivekAutomationPractice\\src\\drivers\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("https://www.youtube.com/");
driver.manage().window().maximize();
Thread.sleep(5000);
driver.findElement(By.xpath("//input[#id='search']")).sendKeys("selenium");
List<WebElement> li=driver.findElements(By.xpath("//*[starts-with(#id,'sbse')]"));
System.out.println(li.size());
li.get(2).click();
}
}
Please try the below code my friend. If this code helps you then I request you to mark it as accepted. This is how Stackoverflow works my friend :)
static{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Sangeeta-Laptop\\Downloads\\chromedriver_win32 (3)\\chromedriver.exe");
}
WebDriver driver = new ChromeDriver();
String urlBase = "https://www.youtube.com";
#BeforeTest
public void beforeTest() {
driver.get(urlBase);
driver.manage().window().maximize();
}
#Test
public void test() throws InterruptedException {
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#id='search']")).sendKeys("selenium");
Thread.sleep(5000);
driver.findElement(By.xpath("//input[#id='search']")).sendKeys(Keys.SPACE);
Thread.sleep(5000);
List<WebElement> li=driver.findElements(By.xpath("//*[starts-with(#id,'sbse')]"));
Thread.sleep(5000);
System.out.println(li.size());
}
#org.testng.annotations.AfterTest
public void AfterTest() {
driver.quit();
}
}
Can you try this
driver.findElements(By.cssSelector("#results ol#search-results>li h3>a"));
My below code does not work. Already checked checkboxes are getting unchecked when I run below code.
Need your suggestions.
'''
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DropboxSelect {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver(); // launch chrome
driver.manage().window().maximize(); // maximize window
driver.manage().deleteAllCookies(); // delete all the
cookies
// dynamic wait
driver.manage().timeouts().pageLoadTimeout(40,
TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
driver.get("https://www.jquery-az.com/boots/demo.php?
ex=63.0_2"); // enter URL
driver.findElement(By.xpath("//button[contains(#class,'multiselect')]")).click();
List<WebElement> list =
driver.findElements(By.xpath("//ul[contains(#class,'multiselect-
container')]//li//a//label"));
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getText());
if (!list.get(i).isSelected()) {
list.get(i).click();
}
}
'''
You could adapt the xpath for your list and the condition if an item is selected as follows:
List<WebElement> list = driver
.findElements(By.xpath("//ul[contains(#class,'multiselect-container')]//li"));
for (WebElement webElement : list) {
System.out.println(webElement.getText());
if (!"active".equals(webElement.getAttribute("class"))) {
webElement.click();
}
}
It works but it is a bit brittle.
I want to use: Login_Page Login = PageFactory.initElements(driver, Login_Page.class); in a unique way in all steps.
When I use it for each step I have no problems, but on the contrary Java shows me the error: " Value driver is always 'null'".
I would also like to replace Thread.sleep (2000); for a better solution.
Here is my Code:
package stepdefs;
import Pages.Login_Page;
import cucumber.api.java.pt.Dado;
import cucumber.api.java.pt.Entao;
import cucumber.api.java.pt.Quando;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import java.util.concurrent.TimeUnit;
public class StepDefinitions {
WebDriver driver;
Login_Page Login = PageFactory.initElements(driver, Login_Page.class);
#Dado("^que que estou na pagina principal do Gmail\\.$")
public void que_que_estou_na_pagina_principal_do_Gmail () throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:\\browsers\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("https://www.gmail.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Quando("^forneco as credenciais validas\\.$")
public void forneco_as_credenciais_validas () throws Exception {
// Login_Page Login = PageFactory.initElements(driver, Login_Page.class);
Login.setEmail("rbkamontana#gmail.com");
Login.ClickOnNextButton();
Thread.sleep(2000);
Login.setSenha("automation10");
Thread.sleep(3000);
Login.ClickOnEnterButton();
driver.manage().window().maximize();
Thread.sleep(3000);
}
#Entao("^posso ver que estou logado\\.$")
public void posso_ver_que_estou_logado () throws Exception {
driver.findElement(By.xpath("//*[#id=\"gb\"]/div[2]/div[3]/div[1]/div[2]/div/a/span")).click();
String stringAtual = driver.findElement(By.xpath("//*[#id=\"gb\"]/div[2]/div[4]/div[1]/div[2]/div[1]")).getText();
String StringEsperada = "Rebeka Montana";
Assert.assertTrue(stringAtual.contains(StringEsperada));
//driver.quit();
}
}
Instead of Thread.sleep you can use selenium WebDriverWait function by a Locator.
Ref:
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html
void waitForElement(By Locator){
WebDriverWait myWait = new WebDriverWait(myDriver, 20);
myWait.until(ExpectedConditions.visibilityOfElementLocated(Locator));
}
Try initiating this inside of a constructor instead:
public StepDefinitions(){
driver = new ChromeDriver();
Login = PageFactory.initElements(driver, Login_Page.class);
}
An instance method is initializing the driver field at runtime, which explains why things work inside the step definition method. The solution is deceptively simple: create a getter method for the page model:
public class StepDefinitions {
WebDriver driver;
Login_Page login;
private Login_Page getLoginPage() {
if (login == null) {
login = PageFactory.initElements(driver, Login_Page.class);
}
return login;
}
#Quando("^forneco as credenciais validas\\.$")
public void forneco_as_credenciais_validas () throws Exception {
Login_Page login = getLoginPage();
login.setEmail("rbkamontana#gmail.com");
login.ClickOnNextButton();
Thread.sleep(2000);
login.setSenha("automation10");
Thread.sleep(3000);
login.ClickOnEnterButton();
driver.manage().window().maximize();
Thread.sleep(3000);
}
I am writing the following code to click on the element with text as My Account. It is showing "element not visible". To resolve the issue I am trying expected wait, but it is being timed out. Is there any way around. You can find my code below:
package com.php.travels;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LogIn {
public static void main(String[] args) {
System.setProperty(
"webdriver.chrome.driver",
"/Users/owner/desktop/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://www.phptravels.net");
try {
WebDriverWait wait=new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//li[#id ='li_myaccount']/a"))
).click();
}
catch(Throwable t){
System.out.println("The execption is: " + t);
}
finally {
System.out.println("If no exception tell me now");
}
}
} // end class
To click() on the element with text as My Account instead of visibilityOfElementLocated() you need to induce WebDriverWait through elementToBeClickable() method and you can use the following solution:
Code Block:
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://www.phptravels.net");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//nav[#class='navbar navbar-default']//li[#id='li_myaccount']/a[normalize-space()='My Account']"))).click();
Browser Snapshot:
Unable to get all links from the webpage - Selenium
Unable to get all links from the webpage by using below mentioned code.
Code below:
package config;
import java.util.concurrent.TimeUnit;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class ActionKeywords {
// WebDriver driver = new FirefoxDriver();
WebDriver driver;
#BeforeTest
public void setup()
{
System.setProperty("webdriver.gecko.driver", "E:\\geckodriver-v0.16.1-win64\\geckodriver.exe");
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability("marionette", true);
driver = new FirefoxDriver(dc);
driver.manage().window().maximize();
}
#Test
public void openBrowser(){
driver.get("https://www.google.com/");
}
/*
#Test
public void verify_Menus(){
WebElement mainMenu = driver.findElement(By.xpath("//ul[#id='menu-main']/li/a"));
System.out.println(mainMenu.getText());
WebElement subMenu = driver.findElement(By.xpath("//a[contains(text(),'Impegno Per La Natura')]"));
Actions action = new Actions (driver);
action.moveToElement(mainMenu).perform();
System.out.println(subMenu.getText());
action.click(subMenu).perform();
} */
#Test
public void all_Links(){
try{
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
System.out.println("Count of all links: " +allLinks.size());
//Loop
for (WebElement link : allLinks)
System.out.println(link.getText());
}catch (Exception e){
System.out.println("Element not found by tagName");
}
}
#AfterTest
public void close_Browser(){
driver.quit();
}
}
After run this program, result displayed as 'Count of all links: 0'
Please advise!
Thanks,
Sudhir
You will get all links using containing the attributes href / src like shown in following code:
#Test
public void alllinks()
{
System.setProperty("webdriver.chrome.driver", "D:/Selenium/Drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.google.com");
List<WebElement> list=driver.findElements(By.xpath("//*[#href or #src]"));
for(WebElement e : list){
String link = e.getAttribute("href");
if(null==link)
link=e.getAttribute("src");
System.out.println(e.getTagName() + "=" + link);
}
}
Hope this code will help you.
Thanks
You are using the correct code But executing in wrong order all_Links() method is executing first before openBrowser().
Please put the priority in your #test annotation because #test annotation run by default alphabetical order.
Hope this will helpful to you!!!
It would be better if you can change driver.get("https://www.google.com/"); from OpenBrowser() to SetUp(). OpenBrowser() is not supposed to be a test and it can be interfering with the order of execution.