Selenium Java Drag and drop - java

I am trying to drag and drop using Selenium Java. It is clicking but not dropping it in the destination specified.
Code used for dragging and dropping:
WebElement drag= driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div[2]/vr-modalbody/div/vr-form/div/vr-validation-group/vr-tabs/vr-tab[3]/vr-row/div/vr-columns/div/vr-validation-group/div/vr-directivewrapper/vr-rules-normalizenumbersettings/div/vr-row[1]/div/vr-columns/div/vr-toolbox/div/div[3]"));
//Drop
WebElement Drop= driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div[2]/vr-modalbody/div/vr-form/div/vr-validation-group/vr-tabs/vr-tab[3]/vr-row/div/vr-columns/div/vr-validation-group/div/vr-directivewrapper/vr-rules-normalizenumbersettings/div/vr-row[2]/div/vr-columns/div/div[2]/div/vr-validator/div/div[1]/vr-datagrid/vr-datagridrows/div[1]/div/div[2]/div[1]"));
Actions actions= new Actions(driver);
actions.clickAndHold(drag).build().perform();
actions.moveToElement(Drop).build().perform();
actions.release(Drop).build().perform();

If this is not working, please share URL or page source code.
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
public class DragAndDropTest extends WebDriverSetup {
public static void main (String[] args) {
WebDriver driver = startChromeDriver(); // standard driver setup just wrapped
driver.get("https://demoqa.com/droppable/");
WebElement draggable = driver.findElement(By.id("draggable"));
WebElement droppable = driver.findElement(By.id("droppable"));
Actions actions = new Actions(driver);
actions.dragAndDrop(draggable, droppable).build().perform();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
driver.quit();
}
}

First, you have to move to the element you want to drag. Besides, you can use chaining.
...(your codes are above)
actions.moveToElement(drag)
.clickAndHold()
.moveToElement(Drop)
.release(Drop).perform();

try {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(drag));
Actions actions = new Actions(driver);
actions.clickAndHold(drag).build().perform();
actions.moveToElement(Drop).build().perform();
actions.release(Drop).build().perform();
} catch (Exception e) {
System.out.println("Error occurred while dragging and dropping: " + e.getMessage());
}

Related

How to automate accept cookies pop-up from java app using Selenium

The app is going to load the system default browser, load a special website, and then login automatically
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class theurl {
public static void main(String[] args) {
String url = "http://www.playok.com/en/spades/";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
But before trying to login, first the cookies should be accepted automatically; is there a simple way to do it rather than using an external library? if not, which library can do the job
I tried this code, but didnt help:
WebDriver Driver = new ChromeDriver();
Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String url = "http://www.playok.com/en/spades/";
Driver.get(url);
Driver.findElement(By.id("cookie_action_close_header")).click();
System.out.println("completed");
To click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:
cssSelector:
Driver.get("http://www.playok.com/en/spades/");
new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.ckbut.but0"))).click();
xpath:
Driver.get("http://www.playok.com/en/spades/");
new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='ckbut but0' and text()='ACCEPT']"))).click();

unable to click on link in tooltip through selenium

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.

Selenium WebElement.click() refreshes the page instead of going to next screen. No response when WebElement.submit() is used

I am learning Selenium and using jetblue.com for test. When I click on "FIND IT" button in homepage by providing all the required values, the page simply refreshes instead of going to the next screen. Can anyone advise where I am going wrong?
I tried using .click() and submit(). but not the control does not go the next page
package testCases;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
public class Calendar {
#Test
public void calControl() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver","C:\\chromedriver_win32\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
WebDriver driver= new ChromeDriver(options);
driver.get("https://www.jetblue.com");
// driver.findElement(By.className("input-group-btn")).click();
Thread.sleep(3000);
// driver.findElement(By.cssSelector("button[class='btn pull-right']")).click();
List<WebElement> count = driver.findElements(By.className("input-group-btn"));
int count1 = driver.findElements(By.className("input-group-btn")).size();
count.get(0).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//table[#class='calendar']//td//span[.=27]")).click();
System.out.println(count1);
for (int i = 0;i<count1;i++)
{
System.out.println(count.get(i).toString());
}
Thread.sleep(3000);
count.get(1).click();
Thread.sleep(3000);
//driver.findElement(By.xpath("//button/span[#class='foreground-sprite-calendarforward']")).click();
List<WebElement> pullRight = driver.findElements(By.cssSelector("button[class='btn pull-right']"));
int count2 = driver.findElements(By.cssSelector("button[class='btn pull-right']")).size();
do
{
pullRight.get(1).click();
} while (driver.findElement(By.xpath("//div/strong[.='March 2018']")).isDisplayed()==false);
List<WebElement> returnDate = driver.findElements(By.xpath("//table[#class='calendar']//td//span[.=8]"));
int returnCount = driver.findElements(By.xpath("//table[#class='calendar']//td//span[.=3]")).size();
returnDate.get(1).click();
//driver.findElement(By.xpath("//input[#class='piejs']")).click(); Find Button
WebElement from = driver.findElement(By.id("jbBookerDepart"));
from.click();
Thread.sleep(2000);
from.sendKeys("DXB");
from.sendKeys(Keys.TAB);
Thread.sleep(2000);
WebElement to = driver.findElement(By.id("jbBookerArrive"));
to.click();
Thread.sleep(2000);
to.sendKeys("SFO");
to.sendKeys(Keys.TAB);
Thread.sleep(2000);
WebElement findButton = driver.findElement(By.xpath("//*[#id='login-search-wrap']/div[3]/div/div[3]/form/input[5]"));
//System.out.println("Value of button:" +driver.findElement(By.xpath("//*[#id='login-search-wrap']/div[3]/div/div[3]/form/input[5]")).toString());
/*Actions a = new Actions(driver);
//a.click(findButton).build().perform();
a.clickAndHold(findButton).doubleClick().build().perform();*/
/*driver.findElement(By.cssSelector("input[value='Find it']")).submit();
driver.findElement(By.xpath("input[value='Find it']")).submit();*/
System.out.println(findButton.isEnabled());
findButton.click();
Thread.sleep(5000);
}
}
That page is probably using anti-selenium software. I debugged your code several times, and here are my observations - I tried do perform some operations by hand, and some by WebDriver, and the result is: If ANY operation is performed by WebDriver, the form will not submit. That even includes opening of the page. They probably set some flag whenever an automated software is performing any action on their page.
Have a look at this answer. I don't know what anti-bot method they may be using, but this could be the first step.

Using alternative to try catch exception for end of page link

Requirement: Go to the link which is a job search for last 3 days.
1) Print job descriptions
2) Click on the next link to go to next page until you reach the last page
Problem: I am using try catch for no such element found for next link when I reach the last page. Using this solution it stops the script, by looking at the JUNIT bar you will not know if the test passed or failed.It is a grey bar since as I used exit. How can I make this code better so that I do not have to use that try catch and see a green bar for a passing test?
Code:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class QAJob {
#Test
public void jobSearch(){
WebDriver driver= new FirefoxDriver();
driver.get("https://www.indeed.com/jobs?as_and=qa+engineer&as_phr=&as_any=&as_not"
+ "=&as_ttl=&as_cmp=&jt=all&st=&salary=&radius=10&l=Bellevue%2C+WA&fromage=7&limit"
+ "=10&sort=date&psf=advsrch");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//code to scroll down to find the rest pages link
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,1000)", "");
// Find and print the number of pages for the search
List<WebElement> search_pages=driver.findElements(By.xpath("//div [contains(#class,'pagination')]//a"));
System.out.println("Number of pages found for this search " + search_pages.size());
while(search_pages.size()!=0){
List<WebElement> job_desc=driver.findElements(By.xpath("//div [contains(#id,'p')][contains(#class,'row')]"));
for(WebElement e:job_desc){
String str_job_desc=e.getText();
System.out.println(str_job_desc);
}
try
{
// closes the pop up that appears
driver.findElement(By.id("popover-x-button")).click();
}
catch (Exception e)
{
}
try
{
//click on next link to go to next page
driver.findElement(By.xpath("//span[contains(#class,'np')][contains(text(),'Next')]")).click();
//scroll down
JavascriptExecutor jse1 = (JavascriptExecutor) driver;
jse1.executeScript("window.scrollBy(0,1000)", "");
}
//when I get the exception(because no next link is available) exit.
catch (org.openqa.selenium.NoSuchElementException e)
{
System.exit(0);
}
}
}
}
Thanks in advance for your time and suggestion.
You can actually re-use the trick used in your code to avoid try-catch block
List<WebElement> popXButton=driver.findElements(By.id("popover-x-button"));
if (popXButton.size()>0){
driver.findElement(By.id("popover-x-button")).click();
}
Same extends to the next block too
List<WebElement> nextVal=driver.findElements(By.xpath("//span[contains(#class,'np')][contains(text(),'Next')]"));
if(nextVal.size()>0){
driver.findElement(By.xpath("//span[contains(#class,'np')][contains(text(),'Next')]")).click();
}
else{
break;//exits while loop!
}

Can't get selenium to click an element

I'm trying to simulate a few clicks for my new program but I'm stuck on the last thing!
I've managed to make selenium open the page and click on the checkbox which shows a rectangle popup with 9 buttons inside it. The only problem is clicking the buttons inside the pop up! I've checked the xpath a few times but Selenium says "No such element"
Here is my code:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class test {
static WebDriver driver;
public static void main(String[] args) {
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
driver = new FirefoxDriver(myprofile);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.runelocus.com/top-rsps-list/vote-1858-GrinderScape%20-%20New%20Website%20and%20Great%20Updates!/");
driver.switchTo().frame(1);
driver.findElement(By.xpath("//*[#id='recaptcha-anchor']/div[5]")).click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.findElement(By.cssSelector("#rc-imageselect-target > table > tbody > tr:nth-child(1) > td:nth-child(2)")).click();
}
}
Link to the problem: http://www.runelocus.com/top-rsps-list/vote-1858-GrinderScape%20-%20New%20Website%20and%20Great%20Updates!/
EDIT:
It creates the new elements after you click the checkbox. How would I click them?
Element you are trying to click is in iframe. We need to switch explicitly to that iframe for selenium to locate that element. Below code worked for me. (Please format Xpath in better readable format.)
driver.get("http://www.runelocus.com/top-rsps-list/vote-1858-GrinderScape%20-%20New%20Website%20and%20Great%20Updates!/");
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
WebElement iframeSwitch = driver.findElement(By.xpath("/html/body/section/div/div/section/div/article/div/div[2]/form/table/tbody/tr/td[1]/div/div/div/iframe"));
driver.switchTo().frame(iframeSwitch);
System.out.println("Switched");
driver.findElement(By.cssSelector("div[class=recaptcha-checkbox-checkmark]")).click();

Categories