Upload photo button not working in Selenium Webdriver
What I have already tired
driver.findElement(uploadPhotoBtn).sendKeys("E:\\photo.png");
Also tried the Robot function
driver.findElement(uploadPhotoBtn).click();
StringSelection ss = new StringSelection(logoPath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
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_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Same Robot function working for another upload button, but while trying to use here, the .click not working that is why unable to use the Robot function.
HTML page source:
> <div ng-show="!status.uploading" ng-class="{ '!isMobile':
> 'mewe-type-1' }" class="uploader-able !isMobile"><!-- ngIf: isMobile
> --><!-- ngIf: !isMobile --><button ng-if="!isMobile" class="btn-action radius ng-scope">Upload Photo</button><!-- end ngIf: !isMobile
> --><input capture="camera" accept="image/*" name="image" type="file" fileread="fileread" file="file" class="ng-isolate-scope"></div>
Console log:
org.openqa.selenium.WebDriverException: unknown error: Element ... is
not clickable at point (314, 477). Other element would receive the
click:
(Session info: chrome=66.0.3359.181) (Driver info:
chromedriver=2.35.528161
This is example of how to add file to upload button, don't quite sure what is path of button, but You have to find element with <input type="file"> element and interact with it:
WebElement uploadPhotoBtn = driver.find(By...); //type="file"
File file = new File(path);
uploadPhotoBtn.sendKeys(file.getAbsolutePath());
...and this is how to get source, if You have some kind of preview
elementPreview.findElement(By.tagName("img")).getAttribute("src");
Hope this helps,
A couple of things:
1) The "Element is not clickable" error means that the upload button is covered somehow. That could be it is disabled, behind some cover, or my favorite, the whole page clear div. Make sure that the button you're trying to click is truly available for clicking...
2) For the .sendKeys() to work, you need to point to the <input type="file"> element. Based on the variable name, you're trying to point to the <button> webelement instead.
As according the Error which you are getting, try to solve it by any of below, replacing click event:
Actions act = new Actions(wd);
act.moveToElement("Your Webelement").click().perform();
OR you can operate with JavaScript functionality,
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", "Your Webelement");
You need to 'type' your file into the input element. Your above send keys command isn't quite right.
Code you can try:
driver.findElement(By.xpath("//input[#name="image"]")).sendKeys("Image Path Here") ;
My answer was criticized at one SO post by #JimEvans, who is a core contributor to the Selenium web automation framework. I learned something from him. This is what he had to say about upload button with <input type="file">.
If you are trying to upload a file, and the page in question uses the standard upload mechanisms provided by HTML, you can do this directly with Selenium itself. The standard HTML mechanism is with an <input type="file"> element. Once you’ve found that file upload element on the page, you can use element.sendKeys("full/path/and/file/name/here");. This is documented in Step 10 of the algorithm for the Element Send Keys command of the W3C WebDriver Specification and is used in several file upload tests in the Selenium project’s test code example.
WebElement upload = d.findElement(By.xpath("//*[#name='filename']"));
Thread.sleep(2000);
Actions action = new Actions(d);
action.moveToElement(upload);
action.click().build().perform();
Thread.sleep(2000);
Related
I've tried
File file = new File("/Users/swapnil.kotwal/Desktop/AntVsGradle.jpg");
driver.findElement(By.xpath("//input[#class='libray_create-resource_choose-file_hidden-input']")).sendKeys(file.getAbsolutePath());
And My HTML is something like below
<div class="libray_create-resource_choose-file">
<button class="btn is-hollow_blue libray_create-resource_choose-file_button undefined">Choose File</button>
<input type="file" class="libray_create-resource_choose-file_hidden-input">
</div>
<div class="library_create-modal_footer">
<button class="btn is-text_only btn-cancel undefined">Cancel</button>
<button class="btn is-filled_blue undefined" disabled="">Add</button>
</div>
I found that file input which is hidden got the file path set properly.
The problem is there Choose File button element is different from file input element //input[#class='libray_create-resource_choose-file_hidden-input']"
There seems to some JS event which make final Add button enable on click of Choose File button.
So, I imported file into file HTML element but how can I enable Add button?
I tried to make that button enabled
WebElement yourButton= driver.findElement(By.className("is-filled_blue"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].removeAttribute('disabled','disabled')",yourButton);
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(yourButton));
It makes that button visible but still not allow to actually click on it.
First let me say that -- I don't program in Java, -- but I do a lot of selenium coding in Python.
When I was looking at this question from purely a selenium view point I noted that you aren't selecting the choose file button prior to sending your input. I would assume that you have to select this button to enable the element - btn is-filled_blue undefined
Here is some pseudocode that might help trigger that button to switch from disabled to enabled.
File file = new File("/Users/swapnil.kotwal/Desktop/AntVsGradle.jpg");
WebElement select_button = driver.findElement(By.xpath("//*[#class='btn is-hollow_blue libray_create-resource_choose-file_button undefined']"));
select_button.click();
WebElement upload_file = driver.findElement(By.xpath("//input[#class='libray_create-resource_choose-file_hidden-input']"));
upload_file.sendKeys(file.getAbsolutePath());
/* You might need to send an Enter, Return or Tab before the
add_file_button changes. This process requires testing on the website.
upload_file.sendKeys(Keys.ENTER);
upload_file.sendKeys(Keys.RETURN);
upload_file.sendKeys(Keys.TAB);
*/
boolean add_file_button_presence = driver.findElement(By.className("is-filled_blue")).isDisplayed();
boolean add_file_button_enabled = driver.findElement(By.className("is-filled_blue")).isEnabled();
if (add_file_button_presence==true && add_file_button_enabled==true)
{
WebElement add_file_button = driver.findElement(By.className("is-filled_blue"));
add_file_button.click();
}
Since I don't normally program in Java the structure and syntax of my pseudocode could be incorrect. If it is please let me know and I will either delete this answer or correct the issues with some research.
That undefined class looks suspect - try removing it by adding another js call:
js.executeScript("arguments[0].style.removeProperty('undefined')",yourButton);
My suggestion would be always limit the usage of JavaScript(JavascriptExecutor) code to an extent it simulates the end user action and not manipulates the application behavior
like enabling a button which is disabled functionally etc.
Our purpose is to simulate the application steps in the same way how an end user would use it.
I would suggest to use any third part tool like AutoIt/Sikuli to handle this case since sending file path doesn't enable the 'Add' button automatically as expected
1)Click on the 'Choose File' button using Selenium which opens the upload window, which is not a web component.
2)Since Upload window is not a web component Selenium doesn't support it.
3)Use any third party tools like AutoIt/Sikuli to handle the Windows upload popup by setting the filepath and submit.
4)As we are uploading the file in the UI in the same way how an end user would do, 'Add' button will be enabled automatically.
AutoIt
Try to use JavascriptExecutor to click it too, before you remove disabled attribute.
WebElement element = driver.findElement(By.xpath("xpath"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
If you use JavascriptExecutor you dont need to make it visible
I managed to upload file by using below hack... I never click on Choose File link/button which was launching Upload File Windows pop-up and by any mean that windows pop-up was not going away.
Tried below options.
1.
select_button.click();
select_button.submit();
action.sendKeys(Keys.ESCAPE).perform();
select_button.sendKeys(Keys.ESCAPE);
robot = new Robot();
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
none of this hiding that pop-up on Mac OS
So, I found a Jugad(#hack in English) I never click on Choose File button which were launching that Upload File Window
public void uploadFile() {
WebElement element = driver.findElement(By.className("libray_create-resource_choose-file_hidden-input"));
element.sendKeys("/Users/swapnil.kotwal/projectName/automation.pdf");
WebElement addButton = driver.findElement(By.className("is-filled_blue"));
// click was important, thanks to this answer in this thread https://stackoverflow.com/a/67095019/1665592
driver.executeScript("arguments[0].click();", addButton);
driver.executeScript("arguments[0].removeAttribute('disabled','disabled'); arguments[0].style = \"\"; arguments[0].style.display = \"block\"; " +
"arguments[0].style.visibility = \"visible\";", addButton);
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(addButton));
addButton.click();
}
i have issues with click(); function using selenium webdriver.
here's the outputHtml :
<button type="button" class="k-button k-primary" tabindex="0" style="width: 50%;">Valider< /button>
i used the findEelement using various xpath like :
- "//button[#class = 'k-button k-primary' and #type = 'button']"
- "//*[contains(#class, 'k-button k-primary') and text()='Valider']"
and still got the error Unable to locate the element
here's the screenshot of the pop-up's Button that i need to click on (button Valider)
Button : Valider
Have you tried actually copying and pasting the selector?
If you are on a Windows machine:
In Google Chrome if you press F12 to open the developer window.
Find the node you are looking for within the DOM and right click on it.
Then go to "Copy" and "Copy XPath" or you can "Copy JS Path"
Then you can paste the path into your code and try it that way.
I prefer to select dom nodes using the JS Path when I am developing with selenium.
The "Copy Full XPath" option is useful during development if you are having problems like you are because it copies the full path all the from the root node.
This feature is available in all major browsers but I am most familiar with developing with Google Chrome.
Are you sure the Element has loaded when you are searching for it? Try a break point before and verify it is available.
In order to handle alerts/pop-ups you need to switch to it
//switch to alert
Alert alert = driver.switchTo().alert();
//accept it
alert.accept();
// or accept it by your code
driver.findElement(By.XPATH("//button[#class = 'k-button k-primary' and #type = 'button']").click();
//dismiss alert
alert.dismiss();
//or dismiss with you code
driver.findElement(YOUR_LOCATOR).click();
//get text
String alertText = alert.getText()
Please check if the pop up is within some frame. If it is then you have to switch to the frame like this
driver.switchTo.frame(iframe locator)
I am new at using Selenium WebDriver to automate test cases. So far (using Selenium and Java), I am able to open the testing website, enter the username and password, and log in. After logging in, however, the user is re-directed to a screen with a security warning that must be accepted before they can access the actual website. To do this, they must click on a button called "I Agree". I can't get Selenium to click the button and, without it, I can't get to the rest of the site to automate. Here is the HTML for the button:
<form name="landingHandlerSF" method="post" action="/apps/bap/secLandingHandler.do">
<input name="userAgreedTerms" value="" type="hidden">
<input name="submit" value="landing" type="hidden">
<input name="buttonAction" value="I Agree" onclick="setValue('agreetoTerms', 'Y')" type="submit">
</form>
Here is the code I have tried (which doesn't work):
WebElement button = driver.findElement(By.name("buttonAction"));
button.click();
Could someone please help me with this?
As per my understanding, page is redirecting to new html page but driver will be pointing to parent page(Login page in your case) , so you may have to switch to child window in order to click on I Agree button.
The following code will switch the driver away from the current window (ie, the login window) to the new window (ie, the security warning). After clicking I Agree that security warning will be closed and the driver will switch back automatically
String thisWindow = driver.getWindowHandle();
Set<String> windowHandles = driver.getWindowHandles();
for (String windowHandle : windowHandles) {
if (!windowHandle.contains(thisWindow)) {
driver.switchTo().window(windowHandle);
}
}
If it is not navigating to new page then it must be under some iframes , in that case you may need to switch to frame and click the button.
Hope this will work.
Try this and let me know what happened.
Did you try to inject JavaScript code into the browser?
driver.executeScript("setValue('agreetoTerms', 'Y')");
or
driver.executeScript("document.getElementsByName('buttonAction')[0].click()");
I am automating mobile website using selenium.
In my test case I need to upload image. There is one camera image with id addimage on click of which file upload popup is shown. Check images of this flow
HTML code for this :
<div class="clearfix">
<ul id="imageList"> </ul>
<div id="uploadimginput">
<a id="addimage" class="sprite camera"> </a>
</div>
<input id="image" class="w0" type="file" name="image">
</div>
Multiple image upload :
From file upload popup i want to open a folder "testimages" and then select an image.
How can I do this in selenium java.
Don't click on the image itself so that the popup will not appear.
In your html code there should be an input element with type file. In your Selenium test you can find the input element and fill it with the path of the image you want to add. Then submit the form around the input element.
The Selenium framework will handle the rest for you. For me it works fine with all browsers.
I think its a cleaner solution than simulation a keyboard.
From what I can see, this is a Window dialog box and it is out of the context of browser, and hence can't be automated directly by Selenium. Hence, you will have to use Robot/Sikuli/Autoit for that.
Below code is the way by using "Robot class" . For using this, do import all the classes from "java.awt package" namely java.awt.Robot, java.awt.event.KeyEvent, java.awt.Toolkit, java.awt.datatransfer.StringSelection, java.awt.AWTException alongwith the rest necessary imports:
Edited the Code for multiple file upload (Works in FF, IE and Chrome):
//Code for clicking on the image button that brings up the window dialog box
...
//Putting all the absolute paths of the pics to upload(here, 3 files)
String arr[] = {"\"D:\\Pic1.jpg\"", "\"D:\\Pic2.jpg\"", "\"D:\\Pic3.jpg\""};
//Copying the path of the file to the clipboard
StringSelection photo = new StringSelection(arr[0]+arr[1]+arr[2]); //Putting the path of the image to upload
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(photo, null);
//Pasting the contents of clipboard in the field "File name" of the Window Pop-up
Thread.sleep(5000); //Some sleep time to detect the window popup
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
//To Click on the "Open" button to upload files
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
In testing a simple website, I find that when using the Firefox webdriver I am unable to get a Javascript calendar window to appear when the button is clicked. I am able to spawn the window in the Selenium IDE but when I run the Java code, the click is registered, but no window is spawned.
The Code I am using to click the Javascript element is:
WebElement element = driver.findElement(By.cssSelector("img[alt=\"Pick a date\"]"));
element.click();
Additional info: The 'cal.gif' image is also not shown when using the webdriver. The problem is NOT switching to the calendar window or selecting and element within, it is simply getting the window to spawn at all.
This is the website under test: Parking Meter
I have searched quite a bit for the solution, either I am not searcher the right keywords or I am missing something obvious, any help would be appreciated.
edit: HTML code for the JS calendar:
<a href="javascript:NewCal('EntryDate','mmddyyyy',false,24)"
<img height="16" width="16" border="0" alt="Pick a date" src="cal.gif"></img>
</a>
What your doing here is wrong. You need to click on the a tag not on the img tag.
Look at the below code, which is working fine for me:
#Test
public void testSO() throws Exception
{
driver.get("http://adam.goucher.ca/parkcalc/index.php");
Thread.sleep(2000);
driver.findElements(By.tagName("a")).get(0).click();
}
Change the index to 0 or 1 accordingly.
Id be using the JavascriptExecutor.
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("<JavaScript.click;");