Unable to open a link in new tab using Actions Class - java

I am trying to open a link in a new tab using selenium java automation code.
Initially i tried with actions class but it wasn't working. Later i tried using the Keys to automate the same thru keyboard actions and it worked. But i wanted to know why am i unable achieve the same with Actions class. Just wanted to if i am doing anything wrong here or is Actions class not suitable for this.
Below is the code snippet i have written.
public class InterviewQuestion {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//System.out.println(System.getProperty("user.dir")+"\\"+"chromedriver.exe");
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\"+"chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.co.in/");
driver.manage().window().maximize();
WebElement GoogleSearchTextBox = driver.findElement(By.xpath("//input[#title='Search']"));
GoogleSearchTextBox.sendKeys("test automation");
GoogleSearchTextBox.sendKeys(Keys.ENTER);
**boolean useActionsClass = false,useKeys = true;**
// finding the required element to be clicked
WebElement RequiredSearchResult = driver.findElement(By.xpath("//div[#class='EIaa9b']/div[1]/div[2]/a"));
if(**useActionsClass**)
{
Actions actions = new Actions(driver);
//actions.moveToElement(RequiredSearchResult).build().perform();
Thread.sleep(5000);
actions.moveToElement(RequiredSearchResult).contextClick(RequiredSearchResult).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
}
if(useKeys)
{
Thread.sleep(5000);
String s = Keys.chord(Keys.CONTROL,Keys.ENTER);
RequiredSearchResult.sendKeys(s);
Set<String> windows = driver.getWindowHandles();
Iterator itr = windows.iterator();
Object FirstWindowHandle = itr.next();
Object SecondWindowHandle = itr.next();
driver.switchTo().window((String) SecondWindowHandle);
Thread.sleep(5000);
//driver.switchTo().window((String) FirstWindowHandle);
}
//driver.quit();
}
}

First, get the link with the help of href attribute from your RequiredSearchResultLink element. once you have the link, use selenium 4 driver.switchTo().newWindow(WindowType.TAB); method to open a new tab. Once the tab is open, just pass your get method, the url which you got from your link field.
If you are not using selenium 4, I will strongly suggest using it, as it will remove lots of unnecessary code from the action class.
Selenium 4 dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
Code with Selenium 4:
driver.get("https://www.google.co.in/");
driver.manage().window().maximize();
WebElement GoogleSearchTextBox = driver.findElement(By.xpath("//input[#title='Search']"));
GoogleSearchTextBox.sendKeys("test automation");
GoogleSearchTextBox.sendKeys(Keys.ENTER);
WebElement RequiredSearchResultLink = driver.findElement(By.xpath("//div[#class='EIaa9b']/div[1]/div[2]/a"));
String href = RequiredSearchResultLink.getAttribute("href");
driver.switchTo().newWindow(WindowType.TAB);
driver.get(href);
Thread.sleep(10);
driver.quit();
}

3 things you need to
Copy the link you need to open in new tab
Open new tab
Paste your link
driver.switchTo().newWindow(WindowType.TAB);
driver.get("your new lin");

Related

Spring Boot Selenium - Github Dropdown Cannot Work. How can I fix it?

I tried to implement a logout test method through selenium in Spring Boot but I cannot detect dropdown menu located top right hand side.
How can I fix it?
Here is the test method shown below.
#Test
#Order(4)
public void logout() throws InterruptedException {
login();
driver.get("https://github.com");
Thread.sleep(1000);
// Header-item position-relative mr-0 d-none d-md-flex
WebElement profileDropdown = driver.findElement(By.cssSelector(".Header-item.position-relative.mr-0.d-none.d-md-flex")); // cannot work
// dropdown-item dropdown-signout
WebElement signOutButton = driver.findElement(By.cssSelector(".dropdown-item.dropdown-signout")); // cannot work
profileDropdown.click();
Thread.sleep(1000);
signOutButton.click();
}
Here is the error part shown below
java.net.SocketException: Connection reset
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".dropdown-item.dropdown-signout"}
1st Edited
String xpathProfile = "//*[#aria-label='View profile and more']";
WebElement profileDropdown = driver.findElement(By.xpath(xpathProfile));
String xpathSignOut = "//button[contains(#class,'dropdown-signout')]";
WebElement signOutButton = driver.findElement(By.xpath(xpathSignOut));
I got this issue shown below.
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(#class,'dropdown-signout')]"}
This is a bad practice to try to locate elements like this, you should be more specific. Given this DOM that you are working with I would try using a selector somewhat like this:
String xpathProfile = "//*[#aria-label='View profile and more']";
String xpathSignOut = "//button[contains(#class,'dropdown-signout')]";
As you can see it's an xpath type selector and I would recommend learning xpath as it is far more readable once you get used to it and it also works in a few edge cases where you wouldn't be able to use css selector.
Also I've noticed that if you make the window size smaller, at some point the profile button you are trying to click is hidden in github, so maybe that is why your button is not getting clicked. You could try setting a specific bigger window size using chromeOptions:
ChromeOptions options = new ChromeOptions();
options.addArgument("--window-size=1920,1080");
ChromeDriver driver = new ChromeDriver(options);
Can you actually see the button when the test is running?
Here is the answer shown below
public void logout() throws InterruptedException {
login();
driver.get("https://github.com");
Thread.sleep(1000);
// Header-item position-relative mr-0 d-none d-md-flex
WebElement profileDropdown = driver.findElement(By.cssSelector(".Header-item.position-relative.mr-0.d-none.d-md-flex"));
profileDropdown.click();
Thread.sleep(1000);
// dropdown-item dropdown-signout
WebElement signOutButton = driver.findElement(By.cssSelector(".dropdown-item.dropdown-signout"));
signOutButton.click();
Thread.sleep(2000);
}

How to handle multiple windows in selenium?

While automating via Selenium WebDriver, I have the below scenario. On a window, I copy the link and want to open the link on the new window(not in the new tab) and want to set focus on the new window. (Here the second window is not the child window of the first window)please help
You can do something like this
WebDriver driverOne=new ChromeDriver();
// navigate to your desired URL
driverOne.get("http://www.yourwebsite.com/");
// Do your stuff and copy the new link
// string newURL;
WebDriver driverSecond=new ChromeDriver();
driverSecond.get(newURL);
driverSecond will have a focus on the new window and once your actions are complete close the driverSecond.
In Selenium 4 (currently in beta), you the following will open a new window then automatically switch to the window:
#Test
public void openNewWindowForTestProjectBlog () {
WebDriver newWindow = driver.switchTo().newWindow(WindowType.WINDOW);
newWindow.get("https://blog.testproject.io/");
System.out.println(driver.getTitle());
}
//assume - multiple windows are opened by clicking link or a button.
Set<String> windows = driver.getWindowHandles();
for (String window : windows)
{
if (driver.getTitle().contains("***Something that is on new window***"))
{
driver.switchTo().window(window);
//To get title of new window
System.out.println(driver.switchTo().window(window).getTitle());
}
}

Slider error always Selenium Webdriver

Use of everything done. No output only shows an error. Have tried all these ways but it only shows an error. Totally lost it. Nothing is moving forward from yesterday. Kindly look into it and please let me know.
public class task {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "g://geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.cheapoair.com/");
driver.manage().deleteAllCookies();
driver.findElement(By.xpath(".//*[#id='ember746']")).sendKeys("DFW");
driver.findElement(By.xpath(".//*[#id='ember751']")).sendKeys("JFK");
driver.findElement(By.xpath(".//*[#id='owFlight']")).click();
driver.findElement(By.xpath(".//*[#id='departCalendar_0']")).click();
driver.findElement(By.xpath(".//*
[#id='calendarCompId']/section/div/div[1]/ol/div[26]/li")).click();
driver.findElement(By.xpath(".//*[#id='ember751']")).sendKeys("JFK");
driver.findElement(By.xpath(".//*[#id='owFlight']")).click();
driver.findElement(By.xpath(".//*
[#id='ember730']/section/form/input")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//WebElement target = driver.findElement(By.xpath(".//*
[#id='DivDepart']/div/div/div[1]/div[2]"));
//WebElement source = driver.findElement(By.xpath(".//*
[#id='DivDepart']/div/div/div[1]/div[1]"));
//a.dragAndDrop(source, target).build().perform();
WebElement slider = driver.findElement(By.xpath(".//*
[#id='DivDepart']/div/div/div[1]/div[2]"));
//WebElement slider = driver.findElement(By.id("DivDepart"));
Actions a = new Actions(driver);
//a.dragAndDropBy(slider, 30, 0).build().perform();
//a.clickAndHold(slider).moveByOffset(30,
0).release(slider).build().perform();
//System.out.println("moved");
//JavascriptExecutor js = (JavascriptExecutor)driver;
org.openqa.selenium.interactions.Action dragAndDrop =
a.clickAndHold(slider).moveByOffset(40,0).release().build();
dragAndDrop.perform();
//js.executeScript("window.scrollBy(200,0)");
}
}
Note :-
In your code I can see clearly that, you have not selected depart date and arrival date and you are directly clicking on "Search Now" button. Validation messages are appearing if you directly click on search button without selecting depart and arrival date. So webdriver is not able to find the slider that your are interested in. Code you have written for slider is working fine. Do not change it.
public class task {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "D:/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.cheapoair.com/");
driver.manage().deleteAllCookies();
driver.findElement(By.xpath(".//*[#id='ember746']")).sendKeys("DFW");
driver.findElement(By.xpath(".//*[#id='ember751']")).sendKeys("JFK");
driver.findElement(By.xpath(".//*[#id='owFlight']")).click();
driver.findElement(By.xpath(".//*[#id='departCalendar_0']")).click();
driver.findElement(By.xpath(".//*[#id='calendarCompId']/section/div/div[1]/ol/div[26]/li")).click();
driver.findElement(By.xpath(".//*[#id='ember751']")).sendKeys("JFK");
driver.findElement(By.xpath(".//*[#id='owFlight']")).click();
//------- Corrections
driver.findElement(By.xpath("//*[#id='departCalendar_0']")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id='calendarCompId']/section/div/div[1]/ol/div[27]/li")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id='calendarCompId']/section/div/div[1]/ol/div[31]/li")).click();
// Corrections--------
driver.findElement(By.xpath(".//*[#id='ember730']/section/form/input")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement target = driver.findElement(By.xpath(".//*[#id='DivDepart']/div/div/div[1]/div[2]"));
WebElement source = driver.findElement(By.xpath(".//*[#id='DivDepart']/div/div/div[1]/div[1]"));
WebElement slider = driver.findElement(By.xpath(".//*[#id='DivDepart']/div/div/div[1]/div[2]"));
((JavascriptExecutor) driver).executeScript("scrollBy(0,500);");
Actions a = new Actions(driver);
org.openqa.selenium.interactions.Action dragAndDrop =
a.clickAndHold(slider).moveByOffset(40,0).release().build();
dragAndDrop.perform();
} }
Just Execute this code, I have executed this and working fine and as expected.
I just picked your code and executed once, After correction now it is working very fine. Your Slider code is perfect no need of change in it.
Issue was you had not written script for selecting dates[departure and arrival]
You can also try this code to move Slider :
Thread.sleep(5000);
Actions builder1 = new Actions(driver);
WebElement zero = driver.findElement(By.xpath(".//*[#id='DivDepart']/div/div/div[1]/div[2]"));
builder1.dragAndDropBy(zero, 1000, 0).perform();
xpath of slider square :- //*[#id='slider-range']/span[1]
Please let me know if it is working at your end.
After entering From/To & date details when user clicks 'Search' button. Then moves to next screen. From there I believe you would like to move the slider. Then try following code and you may have to alter wait based on application need.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Robot rob = new Robot();
rob.keyPress(KeyEvent.VK_PAGE_DOWN);
rob.keyRelease(KeyEvent.VK_PAGE_DOWN);

cant select the tab drag n sortabke in t he link http://demoqa.com/draggable/ (none of the tabs there)

I tried using all known element identifier to select the tabs in the drag n drop options in the link but constantly giving error object cant be located .
can anyone help me.
public class DragnDrop {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "D:\\Auto\\geckodriver-v0.11.1-win32\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://demoqa.com");
driver.findElement(By.xpath(".//*[#id='menu-item-140']/a")).click();
Actions builder = new Actions(driver);
WebElement know = driver.findElement(By.xpath(".//*[#id='tabs']/ul"));
builder.moveToElement(know, 10, 10 ).click().build().perform();
i tried to even use action to click at particular location none worked
As far as I can see, if it's the "Draggable + Sortable" tab you're trying to click, the below should allow that:
WebElement draggableTab = driver.findElement(By.id("ui-id-5"));
draggableTab.click();
I've tried the above (using C#) and it worked fine.
public class DragDrop {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver",
System.getProperty("user.dir") + "\\src\\Browser_Driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://demoqa.com");
driver.findElement(By.xpath(".//*[#id='menu-item-140']/a")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(), 'Draggable + Sortable')]")));
driver.findElement(By.xpath("//a[contains(text(), 'Draggable + Sortable')]")).click();
// code works perfectly for demoqa site
Actions builder = new Actions(driver);
List<WebElement> list = driver.findElements(By.cssSelector("#sortablebox li"));
WebElement source = driver.findElement(By.id("draggablebox"));
WebElement dest1 = list.get(1);
WebElement dest2 = list.get(4);
builder.click(source).clickAndHold().moveToElement(dest1).moveByOffset(0, 10).release().build().perform();
Thread.sleep(2000);
builder.click(source).clickAndHold().moveToElement(dest2).moveByOffset(0, 10).release().build().perform();

Selenium unable to find element in collapsable div

I was trying to automate the Make My Trip site using Selenium. These are the steps I took:
Search for MakeMyTrip in Google -> Done
Open makemytrip and change country to US -> Done
Click on feedback -> Done
Trying to fill feedback form -> Error
It's saying, unable to find the element.
I have tried the following:
1. Tried finding the element by id
2. Tried finding the element by xpath
//div[#class='feedback-form-container']//form[#id='feedbackForm']//input[#id='field_name_NAME']"
Code:
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseURL = "http://www.google.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void makeMyTriptest() throws Exception {
System.out.println("Entered this loop");
driver.get(baseURL + "/?gws_rd=ssl");
driver.findElement(By.id("lst-ib")).sendKeys("makemytrip");
System.out.println("send keys successful");
driver.findElement(By.linkText("Flights - MakeMyTrip")).click();
driver.findElement(By.id("country_links")).click();
driver.findElement(By.xpath("//*[#id='country_dropdown']//p//a[#href='http://us.makemytrip.com/']")).click();
driver.findElement(By.xpath("//div[#id='webklipper-publisher-widget-container-content-expand-collapse']")).click();
//entering feedback details
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//driver.findElement(By.id("field_name_NAME")).sendKeys("SubbaRao");
driver.findElement(By.xpath("//div[#class='feedback-form-container']//form[#id='feedbackForm']//input[#id='field_name_NAME']")).sendKeys("SubbaRao");
//driver.findElement(By.id("field_email_EMAIL")).sendKeys("test#test.com");
}
The Feedback form is located inside an iframe. You have to switch into it's context:
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//WebElement iFrame = driver.findElement(By.xpath("//*[id='print_ticket_overlayiframe']"));
driver.switchTo().defaultContent();
driver.switchTo().frame("webklipper-publisher-widget-container-frame");
//driver.findElement(By.id("field_name_NAME")).sendKeys("SubbaRao");
driver.findElement(By.xpath("//*[#id='field_name_NAME']")).sendKeys("SubbaRao");
now while you are in the iframe, search for the input
Works for me.

Categories