File download in Selenium webdriver using robot class - java

When I Clicked download button using it opens a download pop up in firefox. Its running correctly and saving the files but when i iterate in loop its not saving instead its opening the file.Any solution for below mentioned code it ?
for (int j = 0; j < StoreSelectedYear_size; j++) {
System.out.println(StoreSelectedYear.get(j));
YearSelection(StoreSelectedYear.get(j));
Thread.sleep(5000);
filedownload(i);
}
StoreSelectedYear.clear();
}
}
public void YearSelection(String StoreSelectedYearStr) throws InterruptedException, AWTException {
Select yearselction = new Select(driver.findElement(By.cssSelector("#u14_input")));
yearselction.selectByVisibleText(StoreSelectedYearStr);
Thread.sleep(5000);
}
public void filedownload(int i) throws AWTException, InterruptedException {
driver.findElement(By.xpath("//button[#id='export']")).click();
Thread.sleep(6000);
Robot robot = new Robot();
robot.delay(5000);
// Thread.sleep throws InterruptedException
if (i == 0) {
robot.keyPress(KeyEvent.VK_DOWN);
robot.delay(2000);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_ENTER);
}
Firefox save image:

You could try an alternate solution by getting the src attribute of the download element, and then using an http library such as HttpUnit to make a direct request to download the file.
This has the added benefit that it will do the work of giving you the file as an object easier if you need to validate or manipulate it within your tests if that matches your use case.
I suggest this because if you're doing this for a job, then utilizing a solution that doesn't require manipulating screen coordinates and window position is often always a better option. And there is likely little value in testing the download prompt, since it doesn't exist in the sandbox with your app.
You can retrieve the cookies in use by your current selenium test session with this code just in case this is compelling to you.
Set<Cookie> seleniumCookies = driver.manage().getCookies();
org.apache.http.client.CookieStore cookieStore = new org.apache.http.client.BasicCookieStore();
for (Cookie seleniumCookie : seleniumCookies) {
org.apache.http.impl.cookie.BasicClientCookie basicClientCookie =
new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
basicClientCookie.setDomain(seleniumCookie.getDomain());
basicClientCookie.setExpiryDate(seleniumCookie.getExpiry());
basicClientCookie.setPath(seleniumCookie.getPath());
cookieStore.addCookie(basicClientCookie);
}
return cookieStore;
This will essentially convert your cookies into a form usable by the apache http library, which you can use to make requests to your app without the app realizing you stepped out of selenium. And if your requests make changes to the cookies in this example, then you can re-set the cookies in selenium afterwards with the new versions.

Related

Open new tab in Firefox and Chrome with Selenium is not working

I read a lot of options related with the way to open new windows with Selenium. All the questions and answers are from a few years ago and maybe that's why they are not working to me. And that's why I would like to open this question again.
My first approach was using javascript action:
((JavascriptExecutor) getDriver()).executeScript("window.open('','NewWindow');");
My issue here is the different result in Firefox and Chrome. Firefox opens a new window and Chrome opens a new tab. This means that my test case is not working as expected if I executed in different browsers.
After that I think about a different approach. If I send the shortcut to open a new tab maybe both browsers will work with the same behavior. And here started my nightmare. None of the next options open anything in the current Chrome and Firefox versions:
Send keys concatenate the shortcut:
getDriver().findElement(By.xpath(".//body")).sendKeys(Keys.COMMAND+"T");
Send keys multiple keys sequence:
getDriver().findElement(By.xpath(".//body")).sendKeys(Keys.COMMAND,"T");
Send Keys chord
getDriver().findElement(By.xpath(".//body")).sendKeys(Keys.chord(Keys.COMMAND + "T"));
Using actions
final Actions builder = new Actions(getDriver());
builder.keyDown(Keys.COMMAND).sendKeys("T").perform();
I'm thinking about try with the COMMAND key Down click on any link, but maybe there is an other easy way to open a new tab in different browsers. And this is my question, do you now an efficient way to open a new tab, not a new window, in different browsers with the same action?
ADITIONAL INFORMATION
Selenium version -> 3.141.59
Chrome version -> 79.0.3945.79
Firefox version -> 70.0.1
Thank you in advance.
This may be help you:-
Using JavascriptExecutor:-
Open new blank window:-
((JavascriptExecutor)driver).executeScript("window.open('about:blank','_blank');");
Open new window with specific url:
((JavascriptExecutor)driver).executeScript("window.open('http://www.yahoo.com','_blank');");
Using Robot class:-
Robot class in Selenium is used for simulating keyboard and mouse events. So, in order to open a new tab, we can simulate the keyboard event of pressing Control Key followed by ‘t’ key of the keyboard. After the new tab gets opened, we need to switch focus to it otherwise the driver will try to perform the operation on the parent tab only.
For switching focus, we will be using getWindowHandles() to get the handle of the new tab and then switch focus to it.
//Use robot class to press Ctrl+t keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
//Implicit Wait
//driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
Thread.sleep(2000);
//Switch focus to new tab
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
//Launch URL in the new tab
driver.get("http://google.com");*/
Two approach of Robot Class to Open url in new tab using selenium
public class NewTab
{
public static void main(String[] args) throws InterruptedException, AWTException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.facebook.com/");
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
Set<String> tabs = (Set<String>)driver.getWindowHandles();
for(String tab : tabs)
{
driver.switchTo().window(tab);
System.out.println(driver.getTitle());
if(driver.getTitle().contains("New Tab"))
driver.get("http://www.google.com/");
}
}
}
Another way, without using the for loop
public class NewTab {
public static void main(String[] args) throws InterruptedException, AWTException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
String Base = driver.getWindowHandle();
Set<String> tabs = (Set<String>)driver.getWindowHandles();
tabs.remove(Base);
driver.switchTo().window(tabs.toArray()[0].toString());
driver.get("http://www.facebook.com/");
}
}
Please try below code.
I didn't use javascript.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);
As a user asked how I finally solved this, my solution was this:
// Save the current window reference
final String parentWindow = driver.getWindowHandle();
// Look for the element I would like to click
final WebElement elem = driver.findElement(By.xpath(xpath));
// Create an action to be performed
final Actions builder = new Actions(driver);
// The OSKEY is a global variable where depending on the OS is saved CMD or CTR
// With the special key chord, the program clicks on the element
builder.keyDown(OSKEY).click(elem).perform();
For me is working without browser problems.

How can I close my close my browser or switch to pop up when automating Google sign in?

I am trying to refresh my Selenium knowledge. So, I am writing a script to navigate through my Google account. After I successfully sign in to Google, a pop up appears under my profile icon on the upper right side in Firefox. I no longer get these pop ups when I sign manually. This is probably because of cookies or some other browser setting. I do not care about the reason why this occurs.
However, since it occurs, I believe it may be preventing my script from closing the browser with driver.close(); I also tried driver.quit(); Neither of these are causing the browser to close.
So, I thought I would try switching windows by doing an iteration through the windows. This is not allowing me to select the pop up that appears to close it.
I also tried to create an Alert alert and switch to it:
driver.switchto.alert();
driver.dismiss();
This is not dismissing this pop up in Google either.
In the end, I do not care about this pop up. I know I listed 2 separate issues here. But, in the end, I just want to close the browser. If I can also learn how to switch to this pop up and click the x to close it, that is a bonus.
//Code added here -------------------------
public void sign_out( WebDriver driver )
{
//At this point,I am already signed in. But, that Google pop up appears
//The pop up says "Get to Google faster. Switch your default search engine to Google."
//Wait for "x" to appear
myDynamicElement = (new WebDriverWait(driver, wait_for_element_time)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x_path_x_pop_up)));
//This is set above as a class member
//final String x_path_x_pop_up = "/html/body/div/div[3]/div[1]/div/div/div/div[2]/div[4]/div/a";
WebElement x_icon = driver.findElement(By.xpath(x_path_x_pop_up));
//Click x to close it
x_icon.click();
String myWindowHandle = driver.getWindowHandle();
String subWindowHandle = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandle = iterator.next();
}
driver.switchTo().window(subWindowHandle); // switch to popup window
// driver.switchTo().window(myWindowHandle);
// This never happens now on this click of the profile icon in Google to sign out.
//Click on profile icon
m_profile_icon.click();
//Wait for "Sign Out" button to appear
myDynamicElement = (new WebDriverWait(driver, wait_for_element_time)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x_path_sign_out_button)));
//Get sign out button
WebElement sign_out_button = driver.findElement(By.xpath(x_path_sign_out_button) );
sign_out_button.click();
}
}
Well as long as you are working in Java you can try the Robot framework and sendKeys as a workaround (ALT+F4):
import java.lang.reflect.*;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class RobotUtilities {
public static void sendKeyCombo(String keys[]) {
try {
Robot robot = new Robot();
Class<?> cl = KeyEvent.class;
int [] intKeys = new int [keys.length];
for (int i = 0; i < keys.length; i++) {
Field field = cl.getDeclaredField(keys[i]);
intKeys[i] = field.getInt(field);
robot.keyPress(intKeys[i]);
}
for (int i = keys.length - 1; i >= 0; i--)
robot.keyRelease(intKeys[i]);
}
catch (Throwable e) {
System.err.println(e);
}
}
// main for testing purposes
public static void main(String args[]) {
String [] keys = {"VK_ALT", "VK_F4"};
sendKeyCombo(keys);
}
}
Alternative more robust solution using windowHandles:
I took this from here
You can switch between windows as below:
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
// Continue with original browser (first window)
So, my problem had to do with errors in the JUnit part of my code. I commented out these sections. Once everything was error free, the driver.quit() closed the browser.
I also did some research and found that JUnit does not allow passing class values between different #Test tests. So, I also moved all of my open browser and close browser into the same #Test. This cleaned everything up as well.

Selenium WebDriver : Verify Print Window dialog displayed on the page

I have a scenario to verify Print Properties dialog (Windows component) opening up correctly after clicking on Print link. Aware of Robot utility class in Java which can emulate keyboard events like Escape/Enter etc. to operate on that window.
Is there any way we can verify the new dialog opened up is a Print dialog - something to verify dialog title i.e. Print or retrieve text from that windows dialog or something else which will confirm dialog to be a Print dialog.
The print dialog comes from the os, which selenium can't handle (yet). Therefore you won't be able to check for existence. The only way to I can think of is using a java.awt.Robot, send VK_ESCAPE and assert that the test continues.
As a starter you could try out this:
Runnable r = new Runnable() {
#Override
public void run() {
try {
Robot r = new Robot();
r.delay(1000);
r.keyPress(KeyEvent.VK_ESCAPE);
r.keyRelease(KeyEvent.VK_ESCAPE);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
Actions actions = new Actions(getDriver());
actions.sendKeys(Keys.CONTROL).sendKeys("p");
Thread t = new Thread(r);
t.start();
actions.perform();
//some stupid asserts that we reached here
If you are operating in windows (which I am going to assume you are) you can use the inspect.exe tool that comes along with visual studio. It will allow you to interact with the dialogue box and even send any information that you want accurately including selecting elements from the drop down or any other interaction needed. This even works if you wish to save files using selenium, but to answer your question, you can even use it to detect if that window is indeed there. How you want to proceed from there is your call.
//using System.Windows.Automation;
//using System.Windows.Forms;
AutomationElement desktop = AutomationElement.RootElement;
AutomationElement Firefox = desktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "MozillaWindowClass"));
AutomationElement PrinterComboBox = PrintForm1.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "1139"));
SelectionPattern selectPrinterComboBox = (SelectionPattern)PrinterComboBox.GetCurrentPattern(SelectionPattern.Pattern);
AutomationElement ItemInDropdown = PrinterComboBox.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "SelectPrintMethod"));
SelectionItemPattern ItemInDropdownSelectItem = (SelectionItemPattern)ItemInDropdown.GetCurrentPattern(SelectionItemPattern.Pattern);
ItemInDropdownSelectItem.Select();
AutomationElement OKButton = PrintForm1.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "1"));
InvokePattern ClickOK = (InvokePattern)OKButton.GetCurrentPattern(InvokePattern.Pattern);
ClickOK.Invoke();

capture a downloaded pdf file name with selenium webdriver

Need to capture the the file name of a PDFs which we get by clicking a download link in a URL. I've tried with this code.but, I cannot get the title or url from the second window
kindly help me out with this or suggest me any other methods to handle this...
**code I tried**
#Test
public void pdfname() throws Exception {
driver.get(baseUrl + "/english/investments/iv_funds.htm");
Set<String> winids = driver.getWindowHandles();
Iterator<String> iterate = winids.iterator();
Thread.sleep(3000);
driver.findElement(By.linkText("FUND MATERIALS")).click();
Thread.sleep(3000);
driver.findElement(By.className("sbToggle")).click();
Thread.sleep(3000);
driver.findElement(By.linkText("Fund Details and Performance Update")).click();
driver.findElement(By.id("fundPerformance")).click();
driver.findElement(By.id("fundPerformance")).clear();
driver.findElement(By.id("fundPerformance")).sendKeys("AEGAU");
Thread.sleep(3000);
driver.findElement(By.xpath("//*[#id='perform']")).click();
Thread.sleep(18000);
winids = driver.getWindowHandles();
iterate = winids.iterator();
String firstwindow=iterate.next();
String secondwindow = iterate.next();
System.out.println(firstwindow);
System.out.println(secondwindow);
driver.switchTo().window(secondwindow); //switch to pdf window
Thread.sleep(3000);
System.out.println("url is"+driver.getCurrentUrl());
driver.close();
}
I think you are trying to get the name from a OS system window. Selenium does not interact with the OS. For windows you can use autoit (http://www.autoitscript.com/site/autoit/) to interact with the OS.

How to capture a remote website using Java Selenium

can anyone tell me how I can capture a webpage using Java Selenium? With an example....
See here: Capturing screenshots from remote Selenium RC.
In essence:
"To solve this you can use the captureScreenshotToString and captureEntirePageScreenshotToString commands, which return a Base64 encoded String of the screenshot, which you can then decode and save to disk on your testrunner machine."
I think this is what you are looking for. But try to be mores specific if it is not.
captureEntirePageScreenshot (
filename,kwargs )
Saves the entire contents of the current window canvas to a PNG file.
Contrast this with the
captureScreenshot command, which
captures the contents of the OS
viewport (i.e. whatever is currently
being displayed on the monitor), and
is implemented in the RC only.
Currently this only works in Firefox
when running in chrome mode, and in IE
non-HTA using the EXPERIMENTAL
"Snapsie" utility. The Firefox
implementation is mostly borrowed from
the Screengrab! Firefox extension.
Please see http://www.screengrab.org
and http://snapsie.sourceforge.net/
for details.
Arguments:
* filename - the path to the file to persist the screenshot as. No
filename extension will be appended by
default. Directories will not be
created if they do not exist, and an
exception will be thrown, possibly by
native code.
* kwargs - a kwargs string that modifies the way the screenshot
is captured. Example:
"background=#CCFFDD" . Currently valid
options:
background
the background CSS for the HTML document. This may be useful
to set for capturing screenshots of
less-than-ideal layouts, for example
where absolute positioning causes the
calculation of the canvas dimension to
fail and a black background is exposed
(possibly obscuring black text).
public static void getSnapShot(WebDriver driver, String event) {
{
try {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage originalImage = ImageIO.read(scrFile);
//int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
jpeg.setAlignment(Image.MIDDLE);
++index;
} catch (Exception e) {
e.printStackTrace();
}
}
}
I like to use PhantomJS driver for taking screenshots.
public class Test {
public static void main(String[] args) {
//PhantomJS headless driver
File file = new File("D:\\Webdriver\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
WebDriver driver = new PhantomJSDriver();
//Set Size here
driver.manage().window().setSize(new Dimension(1600,900));
//To wait until the element get visible or invisible.
WebDriverWait wait = new WebDriverWait(driver, 25);
//To access url.
driver.get("https://www.google.co.in");
//For wait until the element get visible.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("lst-ib")));
File shot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(shot, new File("D:\\Webdriver\\Capture.jpg"));
}
}
It takes full page screenshot of chrome webpage.
System.setProperty("webdriver.chrome.driver", "F:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
String baseUrl = "https://www.google.co.in";
driver.get(baseUrl);
String fullscreen =Keys.chord(Keys.F11);
driver.findElement(By.cssSelector("body")).sendKeys(fullscreen);
TakesScreenshot scrShot =((TakesScreenshot)driver);
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
File DestFile=new File("F://test.png");
FileUtils.copyFile(SrcFile, DestFile);
driver.close();
I see a lot of answers explaining screenshots, but just incase you are asking how to get the entire source of the page use the following method:
String pageSource = driver.getPageSource();
Here is a runnable example.

Categories