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();
}
Related
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)
Unable to click on webelement button
I tried to click on button by mouse movement but no success
my outer html is as below :
<button class="btn btn-alt btn-small" type="button" ng-click="ecdapp.uploadBlueprintModalPopup();">
Create
</button>
button xpath is:
//*[#id="page-content"]/div[3]/button
Not seeing the full page source it's hard to tell where your XPath expression is good or not, you can try locating the button using its text instead
//button[normalize-space(text())='Create']
the normalize-space() function is used to discard heading/trailing whitespaces
It might also be the case the button is not immediately available, I would recommend considering using Explicit Wait approach via WebDriverWait class
WebElement myButton = new WebDriverWait(driver, 10)
.until(ExpectedConditions
.elementToBeClickable(By.xpath("//button[normalize-space(text())='Create']")));
myButton.click();
the above code will try to locate the aforementioned button for 10 seconds and click it as soon as it will be present/visible/clickable. Otherwise it will fail with NoSuchElementException
May be the Xpath is wrong. Try the below xpath:
//button[contains(text(),'Create')]
As you can see on the screenshot this Xpath 100% works, if you still won't be able to click on that button, then problem is not with xpath. Let me know if its still fails.
By.xpath("//button[#class = 'btn btn-alt btn-small' and #type = 'button']")
Based on your comment:
I tried this code , but unable to click . element click intercepted: Element ... is not clickable at point (293, 97). Other element would receive the click: ... (Session info: chrome=74.0.3729.169)
I pretty sure I know whats your problem, before u click on this element, something going on the page:
It says - Other element would receive the click, means there is other element above(overlapping) your button(pop up window, page is greyed out(disabled while loading, Some JS running)), so when Selenium trying to click on your button its actually clicking on that blocking element.
Try to click after Thread.Sleep(); wait 5-10 sec.
If this is the case then u need to add condition before find your button to check that element that prevent from clicking on button is disappeared then u click on it.
Try JavaScript executors as below,
WebElement element = driver.findElement(By.xpath("<xpath of button>"));
JavascriptExecutor js= (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
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);
Screenshot
When I click on a button using XPath or CSS methods the button is highlighted for a moment. Then it changes back to the default colour as if the option is not chosen. When the automation is finished I get a user error that the button option was not selected.
I'm writing Java code with the latest Chrome driver. I've also tried Firefoxdriver. I've tried explicit wait and Thread.sleep and nothing worked.
This is the code - Insurance Cover Type Label
driver.findElement(By.xpath("//*[#id=\'content\']/div[4]/div/div[2]/div[14]/div[2]/ul/li[2]/label")).click();
Similar labels on the screen can be clicked and selected. I searched questions and answers on this topic but i can't find a solution. I've added code and front end screen shots.
The problem is that your locator is incorrect (some indexes are off), at least when I checked it in Chrome using $x().
While you can click the LABEL, I would suggest that you avoid the long XPath and instead use the ID for the contained INPUT and then reference the LABEL sibling. I tried it and it worked fine for me.
By.CssSelector("#itemInsured\\.coverSelected1 + label")
Your code seems to be clicking on a label, and not on a button. Even if the label is inside a button, the event may be captured while it bubbles and cancelled. I'd try selecting exactly the object you want to handle the event.
By looking at the screenshot Insurance Cover Type Label, it seems that the button element that you want to interact with, is inside the <lable> tag. So when you are clicking on the button, it is basically clicking on <label> not the <button>. Can you please provide a screenshot of the dom by expanding the tag.
Your locator should be like
By.xpath("//*[#id=\'content\']/div[4]/div/div[2]/div[14]/div[2]/ul/li[2]/label/button");
You just need to include the element in your xpath that is referring to the button element inside the label.
Work with this code (this xpath: //label[contains(text(), 'Comprehensive')]):
public class Sof {
/**
* Specific logger
*/
private static final Logger logger = LoggerFactory.getLogger(Sof.class);
public static void main(String[] args) throws Exception {
final OperatingSystem currentOperatingSystem = OperatingSystem.getCurrentOperatingSystem();
String pathWebdriver = String.format("src/test/resources/drivers/%s/googlechrome/%s/chromedriver%s", currentOperatingSystem.getOperatingSystemDir(),
SystemArchitecture.getCurrentSystemArchitecture().getSystemArchitectureName(), currentOperatingSystem.getSuffixBinary());
if (!new File(pathWebdriver).setExecutable(true)) {
logger.error("ERROR when change setExecutable on " + pathWebdriver);
}
System.setProperty("webdriver.chrome.driver", pathWebdriver);
final ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://services.aviva.ie/direct/product/car.htm?_flowId=motor-flow&_flowExecutionKey=e1s1");
WebElement element = driver.findElement(By.xpath("//label[contains(text(), 'Comprehensive')]"));
element.click();
Thread.sleep(5000);
driver.quit();
}
}
Note:
If you do Web Interface tests with Java + Selenium, I advise you to use the NoraUi Open Source Framework
As per your code attempt you are trying to invoke click() method on the <label> tag which won't be accepting any click.
If you look into the HTML the <label> node have 2 child nodes, an <input> and another <label> node. You can invoke click() on the child <label> tag as follows :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
options.add_argument("--no-sandbox")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
driver.get('https://services.aviva.ie/direct/product/car.htm?_flowId=motor-flow&_flowExecutionKey=e1s1')
element = driver.find_element_by_xpath("//input[#class='radio coverType' and #name='itemInsured.coverSelected' and #value='0101']")
driver.execute_script("return arguments[0].scrollIntoView(true);", element)
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[#for='itemInsured.coverSelected1']"))).click()
Browser Snapshot :
the checkbox is checked be default and can't click on it to uncheck. here is my code but it came back as error saying element is not currently visible and so may not be interacted with. org.openqa.selenium.ElementNotVisibleException.
String checkboxXPath =("//input[contains(#type='checkbox',#name='key_IT_CONFIG.ios.restriction.functionality.enable.camera_checkboxVal')]");
WebElement elementToClick = driver.findElement(By.xpath(checkboxXPath));
elementToClick.click();
Website code
<input type="checkbox" class="uwp_inputCheckBox"
name="key_IT_CONFIG.ios.restriction.functionality.enable.camera_checkboxVal"
id="key_IT_CONFIG.ios.restriction.functionality.enable.camera"
value="true" dir="ltr" hierarchy="false" expand="true"
checkedval="true" uncheckedval="false"
onclick="checkboxChange('IT_CONFIG.ios.restriction.functionality.enable.camera')"
checked="checked">
whole code
whole code http://imageshack.com/a/img661/1720/SIi6Xj.png
I think you should use explicit wait until element get visible. Please check update code here and use it:
String checkboxXPath =("//input[contains(#type='checkbox',#name='key_IT_CONFIG.ios.restriction.functionality.enable.camera_checkboxVal')]");
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(checkboxXPath)));
WebElement elementToClick = driver.findElement(By.xpath(checkboxXPath));
elementToClick.click();
I have a couple suggestions. I'm not sure why your XPath is so complex when you have an ID on the element you want to click. Try this...
driver.findElement(By.id("key_IT_CONFIG.ios.restriction.functionality.enable.camera"));
I'm kinda guessing that won't work. Looking at the HTML, I see the SPAN right above the element that you want to click and it has an onclick on it. I'm guessing that if you click that, it might trigger the click of the checkbox... so let's try that...
driver.findElement(By.cssSelector("span.uwp_checkBoxSpan.uwp_checkBoxChecked"));
You might need to check my spelling on the class names... I couldn't copy/paste since it's a picture.
Since Selenium works on Javascript I would suggest you to test the checkbox clicking thing manually by entering a Javvascript. Here are the step you need to follow:
Execute the test case manually up till where your script failed.
Goto browsers developer tools option->Console. Enter a javascript
command document.getElementById('key_IT_CONFIG.ios.restriction.functionality.enable.camera').click()
If this works then there is no reason why your code shouldn't work.