Unable to drag and drop element for AngularJS application - selenium

I am trying to drag and drop elements on a AngularJS demo site, but I am not able to achieve results.
For my practice I am using https://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/nested , and I am trying to drag & drop 'Item 7 (From dropzone B)' to 'Item 3 (In container 1)'.
I have used .getText() method to ensure that my xpath is pointing to the correct element. But still it is not working. Below is my code:
public void SetUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "F:\\Drivers\\chromedriver.exe");
d = new ChromeDriver();
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
d.get("https://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/nested");
Thread.sleep(2000);
((JavascriptExecutor)d).executeScript("scroll(4,400)");
WebElement src = d.findElement(By.xpath("html/body/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div/div/ul/li[1]/div"));
System.out.println("The src element is:" +src.getText());
WebElement destn = d.findElement(By.xpath("html/body/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/ul/li[1]/div/div[2]/ul/li/div"));
System.out.println("The src element is:" +destn.getText());
org.openqa.selenium.Point pt1 = src.getLocation();
org.openqa.selenium.Point pt2 = destn.getLocation();
int xCord1 = pt1.getX();
int yCord1 = pt1.getY();
int xCord2 = pt2.getX();
int yCord2 = pt2.getY();
System.out.println("The X & Y cordinate of the src is:" +xCord1+ " & " +yCord1);
System.out.println("The X & Y cordinate of the destn is:" +xCord2+ " & " +yCord2);
Actions ac = new Actions(d);
Action dragAndDrop = ac.clickAndHold(src).moveToElement(destn, 334, 661).release(destn).build();
dragAndDrop.perform();
}

Related

Exception: org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

It shows the Stale Element Reference Exception when I try to check whether the alert is displayed or not.
I have used all the following techniques to handle the Alert dialogue box but it shows an Exception.
JS Executor
Robot class
WebDriver Wait
.click() method
Action class
All the Elements are present while I check manually. When I automate it, it shows an exception...
But I don't know where it occurs??!!...
Step Definition Code:
(In this code, I am using Action class)
public void alert_msg_display() throws Throwable {
WebElement x= driver.findElement(By.xpath("//button[#data-hover='LOGIN NOW']")); //Login button path
actionClick(driver, x);
WebElement y= driver.findElement(By.xpath("//md-dialog[#aria-label='Alert']/md-dialog-content/div")); // Alert message text path
String a= y.getText();
WebElement z= driver.findElement(By.xpath("//button[#ng-click='hide()']")); // Alert box close button path
actionClick(driver, z);
String a1 = "Please Enter Branch Id";
driver.findElement(By.xpath("//input[#ng-model='Branchid']")).sendKeys("HO");
actionClick(driver, x);
String b= y.getText();
actionClick(driver, z);
String b1 = "Please Enter Username (Email Id)";
driver.findElement(By.xpath("//input[#ng-model='Username']")).sendKeys("testmail");
actionClick(driver, x);
String c= y.getText();
actionClick(driver, z);
String c1 = "Please Enter Username (Email Id)";
driver.findElement(By.xpath("//input[#ng-model='Username']")).clear();
driver.findElement(By.xpath("//input[#ng-model='Username']")).sendKeys("xxxxx.rt#yyyyy.com");
actionClick(driver, x);
String d= y.getText();
actionClick(driver, z);
String d1 = "Please Enter Password";
driver.findElement(By.xpath("//input[#name='password']")).sendKeys("abcde");
actionClick(driver, x);
String e= y.getText();
actionClick(driver, z);
String e1 = "LOGIN FAILED, PLEASE CHECK YOUR USERNAME OR PASSWORD";
if (a.equals(a1) && b.equals(b1) && c.equals(c1) && d.equals(d1) && e.equals(e1))
test.log(LogStatus.PASS, "Test Case ID: LOG_006 to LOG_010 - Pass");
else
test.log(LogStatus.FAIL, "Test Case ID: LOG_006 to LOG_010 - Fail");
}
Runner File Code
public void actionClick(WebDriver driver, WebElement a) {
Actions action = new Actions(driver);
action.moveToElement(a).click().build().perform();
}
The movement you click on 'Login Now' (x) element the references to x & y will be refreshed. So you can't use the x & y that are pointing to the old references and that will lead to the Statle Element exception.
The solution would be to get the element each time you want to click on the x & y so that you will have the latest reference to the elements.

How can I print all the submenu of main menu in webdriver

I want to print the submenu text of mainmenu of first list[Electronics] of
in selenium webdriver.
url : https://www.flipkart.com
But there is some issue to take the xpath of that sumMenu.
How can I take the xpath and all.
You can try with the following x-path to get all sub menus of main menu "Electronics"
//span[.='Electronics']/following-sibling::ul//li/a
Try the bellow code. Change value the String searchSubMenu = "Electronics"; if you want get text other sub menu, hope this helps.
driver.get("https://www.flipkart.com/");
//wait login popup and click
new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#class='_2AkmmA _29YdH8']")));
driver.findElement(By.xpath("//*[#class='_2AkmmA _29YdH8']")).click();
String searchSubMenu = "Electronics";
int totalSubMenu = driver.findElements(By.xpath("//*[contains(#class,'Wbt_B2')]")).size();
System.out.println("Search for : " +searchSubMenu);
for(int i=1; i<=totalSubMenu; i++) {
String getTextSubMenu = driver.findElement(By.xpath("(//*[contains(#class,'Wbt_B2')])[" +i +"]")).getText();
System.out.println("Get Sub Menu Title : "+ getTextSubMenu);
if (getTextSubMenu.equals(searchSubMenu)) {
driver.findElement(By.xpath("(//*[contains(#class,'Wbt_B2')])[" +i +"]")).click();
Thread.sleep(1000);
String targetAllGetText = driver.findElement(By.xpath("(//*[contains(#class,'_3GtRpC')])[" +i +"]")).getText();
System.out.println(targetAllGetText);
break;
}
}
driver.quit();
It will help you : Please try
String SubMenu = driver.findElement(By.xpath("Xpath of element")).getText();
System.out.println(SubMenu);
if you want Size:
int Size =driver.findElement(By.xpath("Xpath of element"));
System.out.println(Size);

How to write locator for text between div and span (Preferably xpath) which contains non-breaking space (&nbsp)

I want to write xpath for the following div:
<div class='someclass' id='someid'>:TEST SELENIUM 1234<div>
Please note :
tag can be anything such as div, span ,or anchor tag.
can be present anywhere in the text.
What I have tried so far :
//div[contains(text(),":TEST SELENIUM 1234")]
//div[contains(text(),":TEST{ }SELENIUM{ }1234")]
//div[contains(text(),":TEST SELENIUM 1234")]
//div[normalize-space(text()) = ':TEST SELENIUM 1234']
//div[normalize-space(text()) = ':TEST{ }SELENIUM{ }1234']
//div[normalize-space(text()) = ':TEST SELENIUM 1234']
//div[normalize-space(.) = ':TEST SELENIUM 1234']
//div[normalize-space(.) = ':TEST{ }SELENIUM{ }1234']
//div[normalize-space(.) = ':TEST SELENIUM 1234']
//div[normalize-space(.) = ':TEST{\u00a0}SELENIUM{\u00a0}1234']
//div[normalize-space(.) = ':TEST${nbsp}SELENIUM${nbsp}1234']
What has worked for me (thanks to #Andersson)
//div[starts-with(text(), ":TEST") and substring(text(), 7)="SELENIUM" and substring(text(), 16)="1234"]
This is more of a work around and would work only for known Strings.
These are the SO post which I have already followed :
Link1
Link2
Any help will be highly appreciated.
According to the conversation above, you can use this sample xPath builder(JAVA):
public class Test {
public static void main(String[] args) {
String s = ":TEST SELENIUM 1234";
String[] parts = s.split(" ");
StringBuilder xpath = new StringBuilder("//*");
for (int i = 0; i < parts.length; i++){
xpath.append((i == 0) ? "[contains(text(), '" + parts[i] + "')" : " and contains(text(), '" + parts[i] + "')");
}
xpath.append("]");
System.out.println(xpath);
}
}
Output:
//*[contains(text(), ':TEST') and contains(text(), 'SELENIUM') and contains(text(), '1234')]
In Python I would do
required_div = [div for div in driver.find_elements_by_xpath('//div') if div.text == ':TEST SELENIUM 1234'][0]
to find required node by its complete text content ignoring non-breaking space chars
P.S. Again it's just a workaround, but it seem to be quite simple solution

How to get the all element id's of a screen in selenium

How can I get the all element id's of a screen in selenium?
Please refer to this screenshot
Element ID is getting changed every time the page loads. I used contains#id , start-with#id, but it doesn't work every time. Now I want to get all the element id's from the webpage, so I can select the exact element.
My webpage contains input text, buttons, drop-downs.
Use Xpath instead or cssSelector. If you persist on knowing all page ids as a list of String in java, try to execute a javascript function.
// The Firefox driver supports javascript
WebDriver driver = new FirefoxDriver();
// Go to the Google Suggest home page
driver.get("http://www.google.com/webhp?complete=1&hl=en");
ArrayList ids = (ArrayList)((JavascriptExecutor) driver).executeScript(
" var allElements = document.getElementsByTagName('*'); var allIds = []; "
+ " for (var i = 0, n = allElements.length; i < n; ++i) { "
+ " var el = allElements[i]; "
+ " if (el.id) { allIds.push(el.id); } } return allIds; "
);
Regards,
Alan Mehio
London, UK

How to handle Mouseover in Selenium 2 API

String strPrimaryNav = "MEN";
String strSecondaryNav = "Shoes";
String strTertiaryNav = "Golf";
driver.findElement(By.linkText(strPrimaryNav)).click();
WebElement weSecNav = driver.findElement(By.className("secondaryButton").linkText(strSecondaryNav));
Mouse mouse = ((HasInputDevices) driver).getMouse();
mouse.mouseDown(((Locatable)weSecNav).getCoordinates());
//just trying with for loop as the tertiary popup disappears quickly and hence getting ElementNotVisible Exception
for (int i = 0 ; i< 2; i++){
mouse.mouseDown(((Locatable)weSecNav).getCoordinates());
//mouse.mouseMove(((Locatable)weSecNav).getCoordinates(), 0, 0 );
//WebElement weTerNav = driver.findElement(By.className("tertiaryButton").linkText(strTertiaryNav));
WebElement weTerNav = driver.findElement(By.linkText(strTertiaryNav));
boolean isSecDisplayed = ((RenderedWebElement)weTerNav).isDisplayed();
System.out.println("isDisplayed: " + isSecDisplayed);
System.out.println(" " + ((RenderedWebElement)weSecNav).getAttribute("href"));
System.out.println(" " + ((RenderedWebElement)weSecNav).getValueOfCssProperty("action"));
weTerNav.click();
}
I was trying the below code using selenium 2 but, the tertiary popup not stays long to click it and hence getting ElementNotVisible exception at Tertiary click.
You can at least check that the element is visible before you send your click:
Selenium s = new WebDriverBackedSelenium( driver, URL );
s.waitForCondition( "!( document.getElementById('.....') === null )", "20000" );
s.click( .... );
This avoids the exception. I'm not sure there is a way to make the popup stay any longer than it should.