I am very new to Selenium WebDriver with Java. There is a Upload button on a job portal. When I click on that button windows explorer is displayed to choose the file. there are open and cancel buttons on this window. i want to select the cancel button. since it is a windows explorer i cannot inspect the cancel button. how do we write the code for cancelling the button. Thanks in advance.
driver.get("https://my.indeed.com/resume?from=gnav-homepage&co=US&hl=en_US");
driver.manage().window().maximize();
Thread.sleep(3000);
driver.findElement(
By.xpath("//[#id='container']/div/div/div[2]/div/div/div[2]/div/div[1]/div/div[1]/button")).click();
I do not have Java programming skills. I hope the below python code is easy to translate. In my opinion, combining windows action with selenium calls is often flaky.
There is a hidden element called 'upload resume button', you can change the attribute value to see it on the UI, use the send keys method on the element to upload the resume.
from selenium.webdriver import Remote, DesiredCapabilities
driver = Remote(desired_capabilities=DesiredCapabilities.CHROME)
driver.get('https://my.indeed.com/resume?from=gnav-homepage&co=US&hl=en_US')
driver.execute_script(
"document.getElementById('upload-resume-button').setAttribute('class', '')"
)
upload_your_resume = driver.find_element_by_id('upload-resume-button')
upload_your_resume.send_keys(r'C:\test\resume.docx')
The above code worked in my local.
Short answer is you cant, but if you want to upload a local file you can use send_keys on the input field, sending the file path.
Here is a python exemple:
driver.find_element_by_id("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png")
you can use Robot class to simulate native keyboard and mouse actions to interact with windows based pop-ups.
The shortcut to close any opened window is: “Alt + Space +C” – Closes the focused window.
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_ALT);
rb.keyPress(KeyEvent.VK_SPACE);
rb.keyPress(KeyEvent.VK_C);
rb.keyRelease(KeyEvent.VK_C);
rb.keyRelease(KeyEvent.VK_SPACE);
rb.keyRelease(KeyEvent.VK_ALT);
I am automating tests using selenium chromewebdriver 3.7. Whenever I lauch the site, I get a certificate selection popup like the one below
However I am not able to click on the OK button. These are the options I have tried
//I have tried getWindowHandle like this
String handle= driver.getWindowHandle();
this.driver.switchTo().window(handle);
//I have alos tried switching and accept
driver.switchTo().alert().accept();
//I have also tried to force the enter key like this
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
// I also tried this way
Scanner keyboard = new Scanner(System.in);
keyboard.nextLine();
All my trials have failed. How can I click on OK on this popup window?
This is the closest solution I found which is not working Link here
I also had problems with accepting the warning for using a signed certificate. The solution of #eskoba worked like a charm. The functions are NOT final, because I let the enter button press for 10 times. I made this, because the webdriver needs a long time until it actually calls the url. In the meantime he starts pressing already.
In Python:
def threaded_function():
#Calls the website
browser.get(url)
def threaded_function2():
#Presses 10 times
for i in range(0,10):
pyautogui.press('enter')
#Calling the website and pressing 10 times in the same time
thread2 = Thread(target = threaded_function2)
thread2.start()
thread = Thread(target = threaded_function)
thread.start()
If still actual, I had same issue on Mac, and solution was simple:
for chrome is set AutoSelectCertificateForUrls policy like that:
defaults write com.google.Chrome AutoSelectCertificateForUrls -array-add -string '{"pattern":"[*.]example.com","filter":{"ISSUER":{"CN":"**cert issuer**"}, "SUBJECT":{"CN": "**cert name**"}}}'
for safari:
security set-identity-preference -c "**cert name**" -s "**example.com**"
then use it in code like
subprocess.call() in python
I had the same problem and I was able to solve it by using the robot, creating function for the url and passing it to a different thread.
Runnable mlauncher = () -> {
try {
driver.get(url);
} catch (Exception e) {
e.printStackTrace();
}
};
public void myfunction {
try {
Thread mthread = new Thread(mlauncher);
mthread.start
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception e) {
e.printStackTrace();
}
One suggestion would be, use Sikuli to click on OK button in the certificate.
Steps:
Take screenshot of OK button and save it.
Download sikuli-script.jar and add it to Project's Build path.
Take a screenshot of the UI Element to be clicked and save it locally.
Add the following code to the test case.
Screen s=new Screen();
s.click(“image name”);
Other functions Sikuli provides can be found here.
You can also skip being prompted when a certificate is missing, invalid, or self-signed.
You would need to set acceptInsecureCerts in DesiredCapabilities and pass that when you create a driver instance.
for example, in Python:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.CHROME.copy()
caps['acceptInsecureCerts'] = True
driver = webdriver.Chrome(desired_capabilities=caps)
// opening the base URL
driver1.get(baseUrl+"/");
// opening a new tab
driver1.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND + "t");
driver1.get("my URL");
// getting back to the first tab
driver1.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND, Keys.SHIFT, "{");
// I want to signup by clicking the sign up button
driver1.findElement(By.xpath("/html/body/div[1]/header/div[2]/button")).click();
The error that I get after running is :
"Error communicating with the remote browser. It may have died."
But when I run the same code without the navigation, the button click works fine, then it means there is no problem with the xpath.
The information which browser you are using would be very interesting. And the webdriver doesn't need to control the visbile Tab. So i wouldn't let the Browser change the Tab and I would use the "switchTo" Method of the webdriver.
More information to this topic is here.
As #Kikkirej mentuined, i see no reason to use sendKeys to switch between opened tabs. Use Selenium instead, it is a much better approach.
Edit: in addition, try to provide more information, especially the most basic part - the browser you are automating.
I have seen lots of questions and solutions on File upload using Selenium WebDriver on Stack Overflow. But none of them are working for following scenario.
Someone has given a solution as following
// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
But still I can't find window handle. How can I work on that?
I am looking for a solution for the scenario above.
Please check this on any of the following websites.
http://www.uploadify.com/demos/
http://www.zamzar.com/
// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
Hey, that's mine from somewhere :).
In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:
driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");
In the case of the Uploadify web, you're in a pickle, since the upload thing is no input, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).
So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name input. Please, make sure this assumption is true in your case, too.
If not, you could try to jump to it by pressing Alt + N, at least on Windows...
If yes, you can "blindly" type the path into it using the Robot class. In your case, that would be something in the way of:
driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C); // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON); // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH); // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path
r.keyPress(KeyEvent.VK_ENTER); // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);
It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).
For Flash, the only alternative I know (from this discussion) is to use the dark technique:
First, you modify the source code of you the flash application, exposing
internal methods using the ActionScript's ExternalInterface API.
Once exposed, these methods will be callable by JavaScript in the browser.
Second, now that JavaScript can call internal methods in your flash app,
you use WebDriver to make a JavaScript call in the web page, which will
then call into your flash app.
This technique is explained further in the docs of the flash-selenium project.
(http://code.google.com/p/flash-selenium/), but the idea behind the technique
applies just as well to WebDriver.
Below code works for me :
public void test() {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.freepdfconvert.com/pdf-word");
driver.findElement(By.id("clientUpload")).click();
driver.switchTo()
.activeElement()
.sendKeys(
"/home/likewise-open/GLOBAL/123/Documents/filename.txt");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.id("convertButton"));
Using C# and Selenium this code here works for me, NOTE you will want to use a parameter to swap out "localhost" in the FindWindow call for your particular server if it is not localhost and tracking which is the newest dialog open if there is more than one dialog hanging around, but this should get you started:
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using OpenQA.Selenium;
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public static void UploadFile(this IWebDriver webDriver, string fileName)
{
webDriver.FindElement(By.Id("SWFUpload_0")).Click();
var dialogHWnd = FindWindow(null, "Select file(s) to upload by localhost");
var setFocus = SetForegroundWindow(dialogHWnd);
if (setFocus)
{
Thread.Sleep(500);
SendKeys.SendWait(fileName);
SendKeys.SendWait("{ENTER}");
}
}
I made use of sendkeys in shell scripting using a vbsscript file. Below is the code in vbs file,
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "C:\Demo.txt"
WshShell.SendKeys "{ENTER}"
Below is the selenium code line to run this vbs file,
driver.findElement(By.id("uploadname1")).click();
Thread.sleep(1000);
Runtime.getRuntime().exec( "wscript C:/script.vbs" );
Find the element (must be an input element with type="file" attribute) and send the path to the file.
WebElement fileInput = driver.findElement(By.id("uploadFile"));
fileInput.sendKeys("/path/to/file.jpg");
NOTE: If you're using a RemoteWebDriver, you will also have to set a file detector. The default is UselessFileDetector
WebElement fileInput = driver.findElement(By.id("uploadFile"));
driver.setFileDetector(new LocalFileDetector());
fileInput.sendKeys("/path/to/file.jpg");
There is a simpler way to solve this then what Slanec described. Hes solution works when you are using an English keyboard, if not you will have a hard time trying to "map" the key for special characters.
Instead of robot.keyPress and robot.keyRelease every single key you can use Toolkit to copy the String to the clipboard and then paste it.
StringSelection s = new StringSelection("Path to the file");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null);
Robot robot = new Robot();
robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);
robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
robot.keyPress(java.awt.event.KeyEvent.VK_V);
robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);
Thread.sleep(3000);
robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
First add the file to your project resource directory
then
public YourPage uploadFileBtnSendKeys() {
final ClassLoader classLoader = getClass().getClassLoader();
final File file = new File(classLoader.getResource("yourFile.whatever").getPath());
uploadFileBtn.sendKeys(file.getPath());
return this;
}
Walla, you will see your choosen selected file, and have skipped the file explorer window
Import System.Windows.Forms binary to the test solution and call the following two LOC on clicking the Upload button on the UI.
// Send the file path and enter file path and wait.
System.Windows.Forms.SendKeys.SendWait("complete path of the file");
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
An alternative solution would be to write a script to automate the Open File dialog. See AutoIt.
Also, if you can't "click" the element, my workaround is generally to do this:
element.SendKeys(Keys.Enter);
Hope this helps (Even though it's an old post)
Below code works for me:
// wait for the window to appear
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());
// switch to the file upload window
Alert alert = driver.switchTo().alert();
// enter the filename
alert.sendKeys(fileName);
// hit enter
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
// switch back
driver.switchTo().activeElement();
You have put double slash \\ for the entire absolute path to achieve this
Example:- D:\\images\\Lighthouse.jpg
Steps
- use sendkeys for the button having browse option(The button which will open
your window box to select files)
- Now click on the button which is going to upload you file
driver.findElement(By.xpath("//input[#id='files']")).sendKeys("D:\\images\\Lighthouse.jpg");
Thread.sleep(5000);
driver.findElement(By.xpath("//button[#id='Upload']")).click();
Use AutoIt Script To Handle File Upload In Selenium Webdriver. It's working fine for the above scenario.
Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");
Please use below link for further assistance:
http://www.guru99.com/use-autoit-selenium.html
webDriver.FindElement(By.CssSelector("--cssSelector--")).Click();
webDriver.SwitchTo().ActiveElement().SendKeys(fileName);
worked well for me. Taking another approach provided in answer above by Matt in C# .net could also work with Class name #32770 for upload box.
The below one had worked for me
webDriver.findElement(By.xpath("//input[#type='file' and #name='importFile']")).sendKeys("C:/path/to/file.jpg");
Double the backslashes in the path, like this:
driver.findElement(browsebutton).sendKeys("C:\\Users\\Desktop\\Training\\Training.jpg");
I'm creating screenshots in my testcases with selenium webdriver, and while these indeed show what is visible in my web application, it doesn't show popups created by the browser.
I have found that in IE in some cases, my app triggers a JS debug popup in IE. This is of course an error and breaks the rest of my test, but the screenshot does not show the error. I presume this is because it's an IE native popup, rather than one trigger by my application.
Is it possible to get this included in the screenshots? I was thinking of maybe creating the screenshot with Robot#createScreenCapture() but obviously that wouldn't show anything useful if the browser is minimized.
So, a few possible solutions:
- can you detect if an error message pops up in a browser
- is it possible to maximise/focus the browser while running?
- can you take screenshots from selenium with the popups showing?
Selenium will take a screenshot that represents the rendered DOM that the browser shows the end user by intercepting the rendered image that the browser is displaying and taking a copy of it.
It does not take a desktop screenshot so the screenshots shown will not show anything covering the browser window. JavaScript alerts are not part of the rendered DOM so you will not see these in Selenium screenshots.
Maybe because the driver is not with the Alert/Window active?
You could try something like this:
private void CheckForOtherWindows()
{
//Check for any other window open
if (driver.WindowHandles.Count > 0)
{
foreach (string window in driver.WindowHandles)
{
driver.SwitchTo().Window(window);
TakeScreenshot();
}
}
//Check for alert window
try
{
driver.SwitchTo().Alert();
TakeScreenshot();
}
catch
{
//Nothing
}
}
This is not tested, not sure if works. Just giving the idea. :)
Edit:
To maximize the window is easy:
driver.Manage().Window.Maximize();
Hope it helps.
You can use this as below:
FileUtils.copyFile(((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE), new File("E:\\ScreenShot\\screenshot.png"));