Selenium Webdriver (C#): Drag and Drop executed but nothing happens - selenium

I am unable to drag and drop the W3Schools image into the rectangle using the example code people have given before. I've tried Firefox, Chrome and IE webdrivers, nothing is happening.
Firefox version 26.0
Chrome version: 31.0.1650.63 m
Internet Explorer version: 11
FirefoxDriver browser = new FirefoxDriver(); //Open up a Firefox browser
browser.Url = "http://www.w3schools.com/html/html5_draganddrop.asp";
System.Threading.Thread.Sleep(5000); // Wait so I can see what's happening
IWebElement imageToDragAndDrop = browser.FindElementById("drag1");
IWebElement boxToDragImageInto = browser.FindElementById("div2");
Actions actions = new Actions(browser);
// Attempt 1: Calling the DragAndDrop method did not work
// actions.DragAndDrop(imageToDragAndDrop, boxToDragImageInto).Build().Perform();
// Attempt 2: Calling the DragAndDrop method again but with the method calls on separate lines
//actions.DragAndDrop(imageToDragAndDrop, boxToDragImageInto);
//actions.Build();
//actions.Perform();
// Attempt 3: Calling the ClickAndHold, MoveToElement, Release methods did not work either
actions.ClickAndHold(imageToDragAndDrop);
actions.MoveToElement(boxToDragImageInto);
actions.Release(imageToDragAndDrop);
actions.Build();
actions.Perform();

HTML5 drag and drop is a known issue for Selenium;
https://code.google.com/p/selenium/issues/detail?id=6315&thanks=6315&ts=1380031813
Try using javascript directly as explained here;
HTML5 Drag and Drop using Selenium Webdriver for Ruby

Related

Selenium webdriver : Not able to perform Keyboard actions like obj.sendKeys(Keys.chord(Keys.SHIFT, "m")); in Google Chrome

On a web page i have execute SHIFT+m from my keyboard for which i have used Action class but that step getting skipped every time in my code and the execution went to the next step.
Tried with both Action class and Robot class in Cucumber based framework using jUnit
I have tried
Actions obj = new Actions(driver);
obj.sendKeys(Keys.chord(Keys.SHIFT, "m"));
obj.build().perform();
Actions obj = new Actions(driver);
obj.sendKeys(Keys.SHIFT, "m");
I am using macbook pro m2 chip, java version = 17
my pom.xml file is:
I dont see the element where you perform the action to (target). You still need to specify the element I believe.
WebElement clickable = driver.findElement(By.id("clickable"));
new Actions(driver)
.moveToElement(clickable)
.sendKeys("abc")
.perform();

Selenium contextClick() hangs on Edge browser

System.setProperty("webdriver.edge.driver","C:\\EdgeDriver\\" + "MicrosoftWebDriver.exe");
WebDriver driver = new EdgeDriver();
driver.navigate().to("http://www.google.com");
new Actions(driver).moveToElement(driver.findElement(By.id("lst-ib"))).contextClick().build().perform();
if (driver != null) {
driver.close();
}
When I run the above code, a context menu is popped up, but it does not proceed further from that. If I manually click on somewhere else, it proceeds further into the program.
I have checked with other browser/driver, it works without any
problem.
I am using Selenium 2.53 and MicrosoftWebDriver 14393
Any solution for this?
try System.setProperty("webdriver.edge.driver","C:\EdgeDriver\MicrosoftWebDriver.exe");
instead of
System.setProperty("webdriver.edge.driver","C:\EdgeDriver\" + "MicrosoftWebDriver.exe");

KeyPress Enter for Selenium

We are doing automation testing and came around with a situation where i need to download the file from the browser .
In Download when the download button is hit we are coming to the system pop for the download where we need to perform the enter operation .
Can some one help us how to perform the enter or keyboard operation currently we are using robot API but it is not working on grid system ,
Here is my code for robot can it be enhanced and used or do we have any alternate way to do it
******** Code *************
public void downloadReportFromMyExport(WebDriver driver, String downloadSufixId) throws AWTException,
InterruptedException
{
String downloadPrefixId = ConfigProperty.getConfig("downloadPrefixId").trim();
String[] suffix;
suffix = StringUtil.split(downloadSufixId, "TR_EXP_");
String suffixPart = suffix[0];
String completeId = downloadPrefixId.concat(suffixPart);
By id = By.id(completeId);
WebElement element = driver.findElement(id);
element.click();
Robot pressKey = new Robot();
pressKey.keyPress(KeyEvent.VK_ENTER);
pressKey.keyRelease(KeyEvent.VK_ENTER);
threadSleep("5");
pressKey.keyPress(KeyEvent.VK_ALT);
pressKey.keyPress(KeyEvent.VK_F4);
pressKey.keyRelease(KeyEvent.VK_F4);
pressKey.keyRelease(KeyEvent.VK_ALT);
logger.info("Downlaod Complete");
}
In firefox browser,
Solution-1
You can change the browser settings so that it saves all downloads to that location without asking.
Refer below link to know to change that setting in firefox.
https://support.mozilla.org/en-US/kb/startup-home-page-download-settings
Solution-2
By using firefox profile setting you can achieve this.
FirefoxProfile profile=new FirefoxProfile();
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.download.dir","C:\\Users\\Downloads\\"); profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(FirefoxDriver.PROFILE, profile);
WebDriver driver=new FirefoxDriver(dc);
yeah i've encountered the same issue
better change the browser settings to save in a particular path
for handling different browsers like,
in FF,
i've used
in firefox by default the control will be on "OPEN" option so..
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
for IE (to save alt+s,to open alt+O) here im saving the file
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
for chrome
by default,when ever you click dowload button it will save without showing any popups
and i've succeeded hope it helps you
-Ajay

Selenium WebDriver zoom in/out page content

How to change page zoom level in Selenium WebDriver?
I tried:
driver.Keyboard().pressKey(Keys.Control);
driver.Keyboard().pressKey(Keys.Add);
But it doesn't work.
Beware that Selenium assumes the zoom level is at 100%! For example, IE will refuse to start (throws an Exception) when the zoom level is different, because the element locating depends on this and if you changed the zoom level, it would click on wrong elements, at wrong places.
Java
You can use the Keys.chord() method:
WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));
Use cautiously and when you're done, reset the zoom back to 100%:
html.sendKeys(Keys.chord(Keys.CONTROL, "0"));
C#
(since I realized C# bindings don't have the Keys.chord() method)
Or, you can use the Advanced User Interactions API like this (again, Java code, but it should work the same in C#):
WebElement html = driver.findElement(By.tagName("html"));
new Actions(driver)
.sendKeys(html, Keys.CONTROL, Keys.ADD, Keys.NULL)
.perform();
Again, don't forget to reset the zoom afterwards:
new Actions(driver)
.sendKeys(html, Keys.CONTROL, "0", Keys.NULL)
.perform();
Note that the naïve approach
html.sendKeys(Keys.CONTROL, Keys.ADD);
doesn't work, because the Ctrl key is released in this sendKeys() method. The WebElement's sendKeys() is different from the one in Actions. Because of this, the Keys.NULL used in my solution is required.
Here are two ways the zoom level can be altered with Java (one is for Chrome and the other is for Firefox):
Chrome
When using v̲e̲r̲s̲i̲o̲n̲ ̲3̲.̲3̲.̲1 of the Selenium Java Client Driver and C̲h̲r̲o̲m̲e̲D̲r̲i̲v̲e̲r̲ ̲2̲.̲2̲8, the following works (where the number in single quotes represents the zoom level to use; 1 = 100%, 1.5 = 150%, etc.):
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.body.style.zoom = '1.5'");
Firefox
The zoom level can be modified with the following:
1. The aforementioned Java Client Driver
2. G̲e̲c̲k̲o̲D̲r̲i̲v̲e̲r̲ ̲v̲0̲.̲1̲5̲.̲0
3. These classes:
java.awt.Robot
java.awt.event.KeyEvent
First of all, instantiate the Robot class:
Robot robot = new Robot();
This code causes the zoom level to decrease:
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_MINUS);
This code causes the zoom level to increase:
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_EQUALS);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_EQUALS);
Python approach working for me, except you have to specify the zoom level:
driver.execute_script("document.body.style.zoom='zoom %'")
Have 'zoom%' = whatever zoom level you want. (e.g. '67%'). This works for Chromedriver, which doesn't seem to accept the send_keys commands.
Zoom in | Zoom out Feature on Windows
Zoom in
WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));
Zoom out
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
Zoom in | Zoom out Feature on MAC
Zoom in
WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.COMMAND, Keys.ADD));
Zoom out
html.sendKeys(Keys.chord(Keys.COMMAND, Keys.SUBTRACT));
The most robust approach
Before you start with Internet Explorer and Selenium Webdriver Consider these two important rules.
The zoom level :Should be set to default (100%) and
The security zone settings : Should be same for all. The security settings should be set according to your organisation permissions.
How to set this?
Simply go to Internet explorer, do both the stuffs manually. Thats it. No secret.
Do it through your code.
Method 1:
//Move the following line into code format
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");
WebDriver driver= new InternetExplorerDriver(capabilities);
driver.get(baseURl);
//Identify your elements and go ahead testing...
This will definetly not show any error and browser will open and also will navigate to the URL.
BUT This will not identify any element and hence you can not proceed.
Why? Because we have simly suppressed the error and asked IE to open and get that URL. However Selenium will identify elements only if the browser zoom is 100% ie. default. So the final code would be
Method 2 The robust and full proof way:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");
WebDriver driver= new InternetExplorerDriver(capabilities);
driver.get(baseURl);
driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,"0"));
//This is to set the zoom to default value
//Identify your elements and go ahead testing...
Hope this helps. Do let me know if further information is required.
Below snippet will set the browser zoom to 80%
String zoomJS;
JavascriptExecutor js = (JavascriptExecutor) driver;
zoomJS = "document.body.style.zoom='0.8'";
js.executeScript(zoomJS);
I know this is late, but in case if you don't want to use action class (or getting any errors, as I did) you can use pure JavaScript to do so.
Here is the code
((IJavaScriptExecutor) Browser.Driver).ExecuteScript("document.body.style.zoom = '70%';");
For Zoom In to 30%(or any other value you wish but in my case 30%) use
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.body.style.zoom = '30%';");
I am using Python 3.5.; I got the same problem as you. I thought you must use Chrome as browser.
I used PhantomJs to finally solve this problem:
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
browser = webdriver.PhantomJS()
browser.get('http://www.*.com')
print(browser.title)
c=browser.find_element_by_tag_name("body")
c.send_keys(Keys.LEFT_CONTROL+Keys.Add)`
you may use "Keys.chord" method for Zoom out and Zoom in
Zoom OUT
WebElement zoomPage = driver.findElement(By.tagName("html"));
zoomPage.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD))
when you are done with your work and want to reset browser back to 100% then use below code
If you want to click on any element, so before click event you may reset you browser window to 100 % after you may click on it.
zoomPage.sendKeys(Keys.chord(Keys.CONTROL, "0"));
You may user Java script code as well for Zoom OUT
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.body.style.zoom = '110%'");
Changing the zoom level through javascript execution is OK but it only apply to the first page displayed. The succeeding pages will return to 100% zoom level.
The best solution I found so far is to set the Chrome Options' device scale factor.
ChromeOptions options = new ChromeOptions();
options.addArguments("force-device-scale-factor=0.75");
options.addArguments("high-dpi-support=0.75");
WebDriver driver = new ChromeDriver(options);
Seems that approach proposed for C# doesn't work anymore.
Approach for C# that works for me in WebDriver version 2.5 is:
public void ZoomIn()
{
new Actions(Driver)
.SendKeys(Keys.Control).SendKeys(Keys.Add)
.Perform();
}
public void ZoomOut()
{
new Actions(Driver)
.SendKeys(Keys.Control).SendKeys(Keys.Subtract)
.Perform();
}
Using Robot class worked for me:
for(int i=0; i<3; i++){
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_MINUS);
}
this will zoom out 3 times.
11-17-2017 Update
var html = page.FindElement(By.XPath("/html"));
html.SendKeys(Keys.Control + "0" + Keys.Control);
You can use Selenium's driver to execute a script that will zoom in or out for you.
Firefox
await driver.executeScript('document.body.style.MozTransform = "scale(3)"');
await driver.executeScript(
'document.body.style.MozTransformOrigin = "top"'
);
This will result in zooming in by 300% and will scroll to top.
Chrome
await driver.executeScript('document.body.style.zoom = "300%"');

Mouse hover on element

http://www.franchising.com/ ---> Mouse over on (Franchises A-Z) ---> need to click Q
I have tried with the following
WebElement we1=driver.findElement(By.cssSelector("a[href='/franchises/']"));
WebElement we2=driver.findElement(By.cssSelector("a[href='/franchises/q.html']"));
String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";
((JavascriptExecutor) driver).executeScript(js, we2); // I have used the script since the we2 is not visible
Actions builder=new Actions(driver);
builder.moveToElement(we1).perform();
Thread.sleep(5000);
we2.click();
could any one try and share me the code... Still I'm getting "ElementNotVisibleException"
With firefoxdriver, a lot would depend on what version of driver you are using and what version of Firefox you have on your system since native support would differ based on that.
Following works on Chrome :
WebElement link1 = driver.findElementByLinkText("Franchises A-Z");
Actions action = new Actions(driver);
action.moveToElement(link1).click(driver.findElementByXPath("//a[contains(#href,'franchises/b')]")).perform();
Before going in to the code i just want to you to ensure the version of Selenium server you are using. Please make it to the updated version of 2.28.x
Code:
driver = new FirefoxDriver();
driver.get("http://www.franchising.com/franchises/");
Thread.sleep(5000);
WebElement element=driver.findElement(By.xpath("//tr[3]/td/table/tbody/tr/td[4]/a"));
Actions builder = new Actions(driver);
builder.moveToElement(element).build().perform();
Thread.sleep(5000);
it works fine for me. Try this code. I hope this will work.