KeyPress Enter for Selenium - 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

Related

How to find the control present in an iframe using selenium?

I want to find the control present in an iFrame in a webpage using selenium to perform actions like click and setting text in textbox. What is the best way to do that using c# or java language.
By using below code you get controls inside iframe in chrome driver. Install latest selenium chromedriver and place it at C:\chromedriver.exe to below code
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
// Initialize browser
WebDriver driver=new ChromeDriver();
//navigate to url
driver.get("https://demoqa.com/frames");
//Switch to Frame using Index
driver.switchTo().frame(0);
//Identifying the heading in webelement
WebElement frame1Heading= driver.findElement(By.id("sampleHeading"));
//Finding the text of the heading
String frame1Text=frame1Heading.getText();
//Print the heading text
System.out.println(frame1Text);
//closing the driver
driver.close();

How to upload file in headless mode with button tag

I'm trying to run file upload in headless mode, I have tried different ways, but not work. How can I get file upload in headless mode?
The import button in DOM is like below:
enter image description here
It is not input tag, I'm not sure if this will impact on the result ?
I need it to run in headless mode.
Following are all the ways I have tried:
Using WebUI.uploadFile keyword
Not work in default mode and headless mode.
Define custom Keywords like below:
public class MyTools {
#Keyword
def uploadFile (TestObject to, String filePath) {
WebUI.click(to)
WebUI.delay(2)
StringSelection ss = new StringSelection(filePath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.delay(1000)
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.delay(1000) //NOTE THE DELAY (500, 1000, 1500 MIGHT WORK FOR YOU)
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
}
This way can run in default Chrome mode, but will always fail in headless mode.
Use following code:
WebDriver driver = DriverFactory.getWebDriver()
String path = 'D:\\Daily task\\New PW User.csv'
driver.findElement(By.xpath("//*[#id='app']/div/section/div/section[1]/div[1]/div/button")).sendKeys(path);
Not work both in default mode and headless mode.
Can someone help me on this?
Robot class won't work in headless mode, at least it is not that simple.
Besides, I don't think you need it (it is not clear why would you need it in your example). Try changing the uploadFile() method to this:
#Keyword
def uploadFile (TestObject to, String filePath) {
WebUI.click(to)
WebUI.delay(2)
WebElement element = WebUiCommonHelper.findWebElement(to, 30)
element.sendKeys(filePath)
}
NOTE:
You will need to import com.kms.katalon.core.webui.common.WebUiCommonHelper in order to convert a test object to a web element.

Can we open a link in new tab (not a new window)in selenium and give commands for carrying out tasks

Can we open a link in new tab (not a new window) and give commands for carrying out tasks
And is it possible to force selenium to open it in new tab.(just like we do Right click - open in new tab)
and then how to handle the tabs
Selenium does not provide a native way to open a new tab. How ever you can use workarounds. Every browser has some short cut for opening new tabs.You can use sendskeys method to do that.
Try the following code:
WebDriver DRIVER=new FirefoxDriver();
DRIVER.get("http://google.com");
WebElement El1=DRIVER.findElement(By.xpath("//body"));
El1.sendKeys(Keys.CONTROL,"t");
DRIVER.get("http://google.com");
Selenium Supports Mouse Hover actions and Right Click functionality, where user can right click on link and choose to open in new Tab.
WebDriver driver = new FirefoxDriver();
driver.get(URL);
Actions act = new Actions(driver);
WebElement linkpath = driver.Findelement(by.xpath(path of the link));
act.contextclick(linkpath).perform(); // right click
act.sendkeys("T").perform(); // click on new tab

Opening a new tab in the same window session of the browser through Selenium WebDriver?

How to open a new tab in the same window session of the browser through Selenium WebDriver command?
Opening a new tab in the same browser window is possible, see solutions for Firefox:
How to open a new tab using Selenium WebDriver with Java?
Controlling firefox tabs in selenium
The problem is - once you've opened a tab, there is no built-in easy way to switch between tabs. Selenium simply doesn't provide an API for that.
Instead of a tab, open a new browser window.
Yes you can do that , See below my sample code for that :
//OPEN SPECIFIC URL IN BROWSER
driver.get("http://www.toolsqa.com/automation-practice-form/");
//MAXIMIZE BROWSER WINDWO
driver.manage().window().maximize();
//OPEN LINKED URL IN NEW TAB IN SAME BROWSER
String link1 = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.linkText("Partial Link Test")).sendKeys(link1);
Above code will open link1 in new tab. you can run above code to see effect. Above is public link includes testing form.
But as #alecxe told that there is no way to switch between tabs. So better you open new browser window.
Using java script we can easily open new tab in the same window.
public String openNewTab(){
String parentHandle = driverObj.getWindowHandle();
((JavascriptExecutor)driverObj).executeScript("window.open()");
String currentHandle ="";
// below driver is your webdriver object
Set<String> win = driver.getWindowHandles();
Iterator<String> it = win.iterator();
if(win.size() > 1){
while(it.hasNext()){
String handle = it.next();
if (!handle.equalsIgnoreCase(parentHandle)){
driver.switchTo().window(handle);
currentHandle = handle;
}
}
}
else{
System.out.println("Unable to switch");
}
return currentHandle;
}
I am afraid, but there is a way to switch between tab's .
We have successful answers for this problem.
Please find the below link.
switch tabs using Selenium WebDriver with Java
Selenium can switch between tabs.
Python:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
element = driver.find_element_by_css_selector("html") # Gets the full page element, any element works for this
key_code = Keys.CONTROL # Use Keys.COMMAND for Mac
driver.execute_script("window.open();") # Executes Javascript to open a new tab
driver.switch_to.window(1) # Switches to the new tab (at index 1, first tab is index 0)
driver.switch_to.window(0) # Switches to the first tab

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%"');