I try to execute testsuite on a remote host with use of Selenium Standalone Server. It should upload a file. I use code below to handle file uploads:
FileBrowserDialogHandler fileBrowserDialogHandler = new FileBrowserDialogHandler();
fileBrowserDialogHandler.fileUploadDialog(fileSource);
It doesn't work when I execute it remotely, because it is not able to open file chooser window.
Input field looks like this on webpage:
<input type="text" id="file-path">
I replaced current solution with WebElement based one to avoid graphical window, but it doesn't work.
WebElement fileInput = driver.findElement(By.id("filepathelement"));
fileInput.sendKeys(filepath);
Input type is not file, so code below is not working:
driver.findElement(By.id("myUploadElement")).sendKeys("<absolutePathToMyFile>");
Upload a file using Java Selenium: sendKeys() or Robot Class.
This method is to Set the specified file-path to the ClipBoard.
Copy data to ClipBoard as.
WIN [ Ctrl + C ]
MAC [ Command ⌘ + C ] - way to tell full Path of file.
public static void setClipboardData(String filePath) {
StringSelection stringSelection = new StringSelection( filePath );
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
Locate the file on Finder Window and press OK to select the file.
WIN [ Ctrl + V ]
MAC
"Go To Folder" - Command ⌘ + Shift + G.
Paste - Command ⌘ + V and
press OK to open it.
enum Action {
WIN, MAC, LINUX, SEND_KEYS;
}
public static boolean FileUpload(String locator, String filePath, Action type) {
WebDriverWait explicitWait = new WebDriverWait(driver, 10);
WebElement element = explicitWait.until(ExpectedConditions.elementToBeClickable( By.xpath(locator) ));
if( type == Action.SEND_KEYS ) {
element.sendKeys( filePath );
return true;
} else {
try {
element.click();
Thread.sleep( 1000 * 5 );
setClipboardData(filePath);
Robot robot = new Robot();
if( type == Action.MAC ) { // Apple's Unix-based operating system.
// “Go To Folder” on Mac - Hit Command+Shift+G on a Finder window.
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_G);
robot.keyRelease(KeyEvent.VK_G);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_META);
// Paste the clipBoard content - Command ⌘ + V.
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_META);
// Press Enter (GO - To bring up the file.)
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
return true;
} else if ( type == Action.WIN || type == Action.LINUX ) { // Ctrl + V to paste the content.
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
}
robot.delay( 1000 * 4 );
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
return true;
} catch (AWTException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return false;
}
File Upload Test :- You can find fileUploadBytes.html file by clicking on Try it Yourself.
public static void uploadTest( RemoteWebDriver driver ) throws Exception {
//driver.setFileDetector(new LocalFileDetector());
String baseUrl = "file:///D:/fileUploadBytes.html";
driver.get( baseUrl );
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
FileUpload("//input[1]", "D:\\log.txt", Action.SEND_KEYS);
Thread.sleep( 1000 * 10 );
FileUpload("//input[1]", "D:\\DB_SQL.txt", Action.WIN);
Thread.sleep( 1000 * 10 );
driver.quit();
}
For more information see my post.
The file(s) in question should be available on the machine (be it local or remote server) that your program is running on, for example, in your /resources directory
On your local machine, this should work.
chooseFileElement.waitForVisible().type("/file/path/filename.jpg");
clickButton("Attach File");
On Remote Server however, you need to associate a new instance of LocalFileDetector to the <input type=file> element.
LocalFileDetector detector = new LocalFileDetector();
File localFile = detector.getLocalFile("/file/path/filename.jpg");
RemoteWebElement input = (RemoteWebElement) myDriver().findElement(By.id("fileUpload"));
input.setFileDetector(detector);
input.sendKeys(localFile.getAbsolutePath());
clickButton("Attach File");
OK, so I am trying to export a file using Selenium. My browser is IE. When I click on the export button a native windows dialogue box comes up.
Image of the pop up
I have to click on the Save button. For this I tried using AutoIT but its not working.
exportbutton.click();
Thread.sleep(2000);
driver.switchTo().activeElement();
AutoItX x = new AutoItX();
x.winActivate("window name");
x.winWaitActive("window name");
x.controlClick("window name", "", "[CLASS:Button; INSTANCE:2]");
This did not work. So I decided to use Robot class and perform the keyboard clicks Atl + S, as this will also enable the browser to Save the file. That did not work either.
try
{
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
}
catch (AWTException e)
{
e.printStackTrace();
}
There is some problem with the web driver I suppose because I tried printing a line after exportbutton.click() and it did not get printed either.
I am new so I can't understand the problem. Please help me out.
So, the problem was that the cursor gets stuck sometimes when you call the click() function. So as a solution I used the Robot class to move my cursor and click on the export button and then I used Robot class to press Alt+S, which is a keyboard shortcut to save a file in IE.
To click on the button I used
try
{
Robot robot = new Robot();
Thread.sleep(2000);
robot.mouseMove(coordinates.getX()+100,coordinates.getY()-400);
Thread.sleep(2000);
robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
catch (AWTException e)
{
e.printStackTrace();
}
To get the coordinates in the above snippet I used the following line
Point coordinates = driver.findElement(By.id("id")).getLocation();
System.out.println("Co-ordinates"+coordinates);
And to press Alt+S I used the following code
try
{
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
}
catch (AWTException e)
{
e.printStackTrace();
}
I had the same problem. I came to realization that
button.click()
does not work very well in this case (with IE driver). So instead of clicking the button I tried this:
robot = new Robot();
button.sendKeys("""");
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
This just gives focus on button and 'presses' it by hitting enter.
Sorry, I wrote approach how to upload the file. If you want to download - use the same approach, but use another buttons: Instead buttons Cntrl + V you can use button Tab to find control of Save/Save as and then Press Enter. Before it, you can paste String with file path ( directory where you want to upload your file).
Auto IT is not required to handle this. just use the below code and it works fine.
If we give element.click on the element, control stops there and hence we use element.sendkeys("") and robot.keyPress(KeyEvent.VK_ENTER);
Below is the complete code:
Robot robot = new Robot();
//get the focus on the element..don't use click since it stalls the driver
element.sendKeys("");
//simulate pressing enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
//wait for the modal dialog to open
Thread.sleep(2000);
//press s key to save
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(2000);
//press enter to save the file with default name and in default location
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
I used AutoIt and it works in windows 10. Refer to the below AutoIt script :
Sleep(9000);
Local $hIE = WinGetHandle("[Class:IEFrame]");
Local $hCtrl = ControlGetHandle($hIE, "", "[ClassNN:DirectUIHWND1]");
If WinExists($hIE,"") Then
WinActivate($hIE,"");
ControlSend($hIE ,"",$hCtrl,"{F6}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{ENTER}");
EndIf
Sleep(5000);
If WinExists($hIE,"") Then
WinActivate($hIE,"");
ControlSend($hIE ,"",$hCtrl,"{F6}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{ENTER}");
EndIf
Sleep(5000);
It clicks the save button and also closes the next alert.
Please adjust Sleep() accordingly.
This is a hack by Dave Haefner. If you don't care if a file was downloaded or not and you want to confirm only that a file can be downloaded, you can use an HTTP request. Instead of downloading the file you'll receive the header information for the file which contains things like the content type and length. With this information, you can confirm the file is you expect.
String link = driver.findElement(By.cssSelector("download-link-element")).getAttribute("href");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpHead request = new HttpHead(link);
HttpResponse response = httpClient.execute(request);
String contentType = response.getFirstHeader("Content-Type").getValue();
int contentLength = Integer.parseInt(response.getFirstHeader("Content-Length").getValue());
assertThat(contentType, is("application/octet-stream"));
assertThat(contentLength, is(not(0)));
I have one website in which When I click on button, it open new tab with link in same browser.
I want to tell selenium to focus on that recently open tab.
I tried many methods but none of them seem helpful in my case.
I have tried :
Method 1 :
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.TAB);
Method 2 :
((JavascriptExecutor) webDriver).executeScript("window.focus();");
Method 3:
driver.switchTo().window(driver.getWindowHandles().last());
Try this code, use Java Robot. that worked for me.
ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
System.out.println(tabs2.size());
for (int i = tabs2.size()-1; i>=0; i--) {
Thread.sleep(2000);
driver.switchTo().window(tabs2.get(i));
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_CONTROL);
System.out.println(driver.getTitle() + "i: " + i);
// do what you needed
}
When I launch a website from Eclipse (selenium) it pops up a authentication box as below:
Here I am unable to enter Username and password, here are the things I tried:
1) Switching of Handle to pop up and identifying Xpath
2) Sending Username and Password in the URL (How to handle login pop up window using Selenium WebDriver?)
3) Sikuli (but requires image capture when executed in different system)
4) Using Robot function
Robot rb = new Robot();
StringSelection username = new StringSelection("XXXXX");
System.out.println("Entering username");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(username, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
//tab to password entry field
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(2000);
//Enter password by ctrl-v
StringSelection pwd = new StringSelection("YYYYYYY");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pwd, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
//press enter
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
None of the above worked till now, just after reaching the website (driver.get(URL)) the control does not seem to come back to eclipse
Use AutoIT scripts to fill that windows. That is the only way to elegantly handle this issue in Windows with Selenium. Check Handle Windows based Authentication Pop Up in Selenium using AutoIt at http://www.toolsqa.com/selenium-webdriver/autoit-selenium-webdriver/
The below code should work, it can be refactored :)
driver.navigate().to("url");
StringSelection selection = new StringSelection("username");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
Thread.sleep(5000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.delay(2000);
selection = new StringSelection("password");
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
I've been trying to use Robot from awt, to input some text on a app. The problem it's that i can't make it type any letters like ê, à or á.
I have tried doing this such printing ^e for example but even that works, it just dosen't print anything for VK_CIRCUMFLEX
Not sure if it matters but i'm testing on a Mac.
Any help would be well come.
You can use the clipboard combined with CTRL/COMMAND+V to do the job for you. The code below works on Windows at least (Mac key combo probably requires a different sequence to do a paste).
public static void main(String[] args) throws AWTException {
String osName = System.getProperty("os.name");
boolean isOSX = osName.startsWith("Mac OS X");
boolean isWin = osName.startsWith("Windows");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection str = new StringSelection("Héllõ Wörld");
clipboard.setContents(str, str);
Robot robot = new Robot();
if (isMac) {
// ⌘-V on Mac
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_META);
} else if (isWin) {
// Ctrl-V on Win
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
} else {
throw new AssertionError("Not tested on "+osName);
}
}