How can I get Selenium WebDriver (Java) to click this button? - java

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()");

Related

Selenium Upload File On file selection doesn't enable submit button

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();
}

Unable to locate and click checkbox ::before using Selenium Webdriver

I'm trying to click a checkbox but it's keep clicking the link 'terms and conditions'. Although my xpath (mentioned below) work on a minimized window but it's failing to click the checkbox when the window is maximized because the href (image) appears in the second line next to checkbox. Looking for some suggestions on clicking the checkbox widget on maximized window. I need to get a focus on it.
Interestingly, when i hover over the ::before (css selector) only than the widget gets highlighted.
<div class="checkbox u-mar-bot-5">
<div class="checkbox__container">
<input class="checkbox__input" type="checkbox" id="basket-contact-terms" required data-parsley-multiple="basket-contact-terms" style>
<label class="checkbox__label checkbox__label--has-link checkbox__label--small" for="basket-contact-terms" style>
::before
"I have read and agree to " <a class="text-link text-link--base text-link- small" href="/terms-conditions" target="_blank">Terms and Conditions</a>
</label>
</div>
</div>
image: Terms and Conditions
I tried a few options that keep failing to check the box and instead the link 'terms and conditions' gets the click. I must be missing something basic.
driver.findElement(By.xpath("//label[#for='basket-contact-terms']")).click();
driver.findElement(By.xpath("//label[contains(#class,'checkbox__label checkbox__label--has-link checkbox__label--small')]")).click();
I did looked around and found someone suggested to use this (below) so i tried but didn't work:
WebElement elem = driver.findElement(By.xpath("//div[contains(#class,'checkbox u-mar-bot-5')]"));
Actions action = new Actions(driver);
action.moveToElement(elem).click().build().perform();
Any suggestion would be appreciated.
Since you tried the ID of the INPUT and it threw an error that it wasn't visible, I would first try a wait to see if it will become visible. (I'm assuming it won't but it's worth a try first).
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.id("basket-contact-terms"))).click();
If that doesn't work, I would next try to click a different position on the element. By default, Selenium clicks on the center of the element. In your case, I think this is what's causing the issue. You can use Actions to click the upper left (1,1) of the element.
WebElement label = driver.findElement(By.xpath("//label[#for='basket-contact-terms']"));
new Actions(driver).moveToElement(label, 1, 1).click().perform();
You can try with
WebElement elem = driver.findElement(By.id("basket-contact-terms"))

button click() does not provide any response

I'm having issues with logging into specific website via HtmlUnit methods.
The site form's submit button looks like this:
<td>
<input type="button" value="Login!" onclick="encPass(UTM_STUDIO_ADMIN);" class="normalButton">
</td>
Mine code snippet:
final HtmlButtonInput submitLogin = form.getInputByValue("Login!");
HtmlPage returnPage = submitLogin.click();
System.out.println(returnPage.asText());
Yet, it prints the logging site with username and password fields fulfilled, that's all.
WebClient config:
wclient.getOptions().setPrintContentOnFailingStatusCode(false);
wclient.getOptions().setCssEnabled(false);
wclient.getOptions().setThrowExceptionOnFailingStatusCode(false);
wclient.getOptions().setThrowExceptionOnScriptError(false);
wclient.getOptions().setUseInsecureSSL(true);
wclient.getOptions().setJavaScriptEnabled(false);
I've been already trying to log via my own added button, and played with ideas of waiting, enabling JS, redirecting etc., but I'm new in the topic so it does not guarantee I can uncheck any ideas as already tried.
Your button is of type button (not submit). In this case the browser renders only a button but the application developer is responsible for doing something if the user clicks the button. In you case the button will trigger some javascript.
But you have disabled Javscript by
wclient.getOptions().setJavaScriptEnabled(false);
Maybe your problem goes away if you enable javascript.
In general it is a good idea to start with the default setting when facing any problems. The defaults are set in a way to be as close as possible to the real browsers.

How to make the hidden element visible using java script executor

Currently am working on Selenium Webdriver with Java
Am trying to click on a button but i can't able to click because it is hidden. Please let me know how to make the hidden element visible 1st then how can click the button.
Please give me some example and my HTML tag is:
<input id="iskpiFilterAction" type="hidden" value="1" name="isKpiFilterAction">
Hmm, your question doesn't make sense for me. But I can exactly answer for your question.
For selenium 2 (webdriver):
WebDriver driver = ...
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("document.getElementById('iskpiFilterAction').type = 'button';");
Result is:
This code causes changing type of element (from hidden to button), but it doesn't make sense for all of us. These two elements have different purpose/use. For more information see:
Original purpose of <input type="hidden">?
What's the point of having hidden input in HTML? What are common uses for this?
http://www.w3schools.com/jsref/dom_obj_hidden.asp
I didnt quiet understand the question.. However .. if you have a hidden object which you want to unhide dynamically using JavaScript using some trigger, this is a way you could do that:
<head>
<script>
function unhide()
{
document.getElementById("iskpiFilterAction").type = "button";
}
</script>
</head>
<body onload="unhide()">
<input id="iskpiFilterAction" type="hidden" value="1" name="isKpiFilterAction">
</body>
I am using body onload event to unhide the object so the moment this page loads you will see the button which u can then click. However if you want it some be triggered at some other event you can use the function accordingly.
Hope it helps.
Try this:
WebElement element = driver.findElement(By.id("iskpiFilterAction"));
((JavascriptExecutor) driver).executeScript("arguments[0].style.type = 'button';", element);

Selenium RC skips onclick() event after click on element

I've got problem I can't deal with. I've tried to search answer in google, tried few things but it doesn't work any way.
Here is the problem:
I'm testing a log in page, where I type in login, password and click "login" button. Everything is OK, I'm logging to the page... But before log in (after click "login" button) there should appear a prompt with some info and "OK" button, the prompt is onclick() event of "login" button. I have no idea why the prompt doesn't show up, and I really need this prompt (I have similar problem with prompt "Do you want to save changes" which also doesn't appear - I assumed that selenium.click(..,..) and webelement.click() somehow bypass onclick() events. Do you have any idea what to do to have onclick() events working properly? I'm using IE (I have to) and selenium webdriver.
Ps.:if I do same actions "manually" the prompts do appear so I don't think that its a mistake in javascript.
Ps2.: Help me please I'm trying to fix it for a 5 h...:(
button code:
<input id="loginForm:loginCmdTest" type="submit" onclick="showAlertAndSubmitForm ();clear_loginForm();" value="Login" name="loginForm:loginCmdTest">
java code:
selenium.type("id=loginForm:login", login);
selenium.type("id=loginForm:pass", pass);
selenium.click("id=loginForm:loginCmdTest");
Ps.3: ANYONE?? Any idea?
Plain guess: You are using old, depreceated Selenium RC. What happens if you transfer it to webdriver approach?
Sample code:
WebDriver driver = new FirefoxDriver();
driver.get("http://your-test-site.com");
driver.findElement(By.id("loginForm:login")).sendKeys("login");
driver.findElement(By.id("loginForm:pass")).sendKeys("pass");
driver.findElement(By.id("loginForm:loginCmdTest").click();

Categories