i have the follow problem:
I have a button inside a form (the web page have a login and password text box and a button), this button calls a js funtion and after the login and password validation, calls the main web page. The html code is this (this code is inside of a form calls "login" and method = POST):
<INPUT class="btn btn-mini btn-primary" onclick=submitForm(); type=button value="Sign On">
In Selenium i try with the follow statements, but without success:
driver.findElement(By.xpath("//input[#type='button']")).click();
driver.findElement(By.cssSelector("input[type='button'][#value='Sign On']")).click();
driver.findElement(By.xpath("//input[#value='Sign On']")).click();
when i run the script, login and password text are filled correctly, but the click in the button it's no working.
Could you help me with this?
Thanks!
Gonzalo from Chile
To click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.btn.btn-mini.btn-primary[value='Sign On'][onclick^='submitForm']"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#class='btn btn-mini btn-primary' and #value='Sign On'][starts-with(#onclick, 'submitForm')]"))).click();
i found the solution, reading a lots of issues related with this. I'm working with win 10 and IE 11, so, Selenium has a problem with this, because need the size of the text, apps, and others items in 100%. In my case, i had this configuration in 150%. Fixing this, i run the script one again and it works.
The code used is:
WebElement button = null;
List<WebElement> inputs = webDriver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
if (input.getAttribute("value").equals("Log In")) {
button = input;
break;
}
}
if (button == null) {
System.err.println("Cannot find button!");
} else {
System.out.println("Clicking button now!");
button.click();
}
After this, i check another code more efficient:
driver.findElement(By.cssSelector("input[type='button'][value='Sign On']")).click();
This works too.
thanks all off you for your help
Related
I am using selenium for my testing a retail website . Once I reached the Checkout page , I am selecting the option as Paypal Where a sandbox url is opening.
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-07L974777B231831F#/checkout/login
I am able to enter the username and password , clicked on Login button.
After that I am redirected to "Agree & Continue " Page . Where I could not perform any action.
I could see clearly the button properties as below
I have tried the below code, but could not perform any action.
WebElement AgreeandContinue= driver.findElement(By.tagName("input"));
AgreeandContinue.click();
You might have many input elements in the same page. What about trying to select by class or id?
WebElement AgreeandContinue= driver.findElement(By.ByClassName('btn'));
or
WebElement AgreeandContinue= driver.findElement(By.ByClassName('continueButton'));
then using submit() instead of click() as the element is a 'submit' type`
FYI : https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebElement.html
Looks like the button has an id defined, so that would be the best locator to use: driver.findElement(By.id("confirmButtonTop));
If that doesn't work, then you might have to add some waits for the button to be clickable.
And if that still doesn't work, then it's possible, as it is with many commercial tools, that the button is actually inside a different iframe. Look further up in the html to confirm if this is the case (it'll have a iframe tag). If that's the case, then you'll have to first switch to the iframe before clicking the button: driver.switchTo().frame(...) . How to identify and switch to the frame in selenium webdriver when frame does not have id
If we look at the HTML you have provided the WebElement with value Agree & Continue is within an <input> tag. So we have to construct a unique css or xpath to identify the WebElement as follows:
cssSelector :
WebElement AgreeandContinue= driver.findElement(By.cssSelector("input#confirmButtonTop"));
OR
xpath :
WebElement AgreeandContinue= driver.findElement(By.xpath("//input[#id='confirmButtonTop']"));
Try with ID, but if it is not you can try with other locators , I suggest you have to use xpaths:
driver.findElement(By.xpath("//input[contains(#id,'confirmButtonTop')]")).click();
or
driver.findElement(By.xpath("//*[contains(#id,'confirmButtonTop')]")).click();
also I will suggest that you can use wait until element to be clickable or visible
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[contains(#id,'confirmButtonTop')]")));
driver.findElement(By.xpath("//input[contains(#id,'confirmButtonTop')]")).click();
or
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(#id,'confirmButtonTop')]")));
driver.findElement(By.xpath("//*[contains(#id,'confirmButtonTop')]")).click();
I want my program to log into indeed.ca (this is working, as long as you enter correct user credentials), navigate to a specific job posting(working), click on the first orange apply button(working), a modal pops up.
Then I want to click on the blue apply button in modal that appears. This is not working. I have commented out my attempt at this portion of the program.
Any help would be much appreciated.
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Testing {
public static void main(String[] args) throws IOException {
//enter location of gecko driver
System.setProperty("webdriver.gecko.driver", "C:\\Users\\Padoga\\Documents\\geckodriver-v0.18.0-win64\\geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
//login works correctly (given that you use proper credentials)
driver.get("https://secure.indeed.com/account/login?service=my&hl=en_CA&co=CA");
driver.findElement(By.xpath("//*[#id=\"signin_email\"]")).sendKeys("abc#gmail.com");
driver.findElement(By.xpath("//*[#id=\"signin_password\"]")).sendKeys("enterPassword");
driver.findElement(By.xpath("//*[#id=\"loginform\"]/button")).click();
//once logged in navigate to specific job
driver.navigate().to("https://ca.indeed.com/cmp/KGHM-International-Ltd./jobs/Financial-Analyst-7a08f1634e7d5c5c");
//clicking on first apply button(orange button) works correctly
Thread.sleep(3000);
driver.findElement(By.xpath("//*[#id=\"apply-state-picker-container\"]/div[1]/span[1]")).click();
//below not working, trying to click on apply button(blue apply button) in popup modal
//I've tried so many different xpaths and ids none seem to be triggering the apply button in modal
Thread.sleep(3000);
driver.switchTo().frame("indeedapply-modal-preload-iframe");
driver.findElement(By.id("apply")).click();
}
}
And here is the various html / javascript? that I have been trying to click on
i.e used as By.id, By.xpath, or By.className, none are working
The below code does not show up when I inspect the page source, only when I inspect the blue apply button in the modal that pops up after clicking the orange apply button, do I see the below code:
<div class="button_outter" id="apply-div">
<div class="button_inner">
<input class="button_content" id="apply" type="submit" name="apply" value="Apply">
</div>
</div>
I have tried using the switch to Iframe, but this is not working in this case. Can you check the below sendkeys approach after clicking the first apply button.
Actions act = new Actions(driver);
act.sendKeys(Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.ENTER);
or
driver.findElement(By.xpath("//body")).sendKeys(Keys.TAB, Keys.TAB,Keys.TAB, Keys.TAB, Keys.ENTER);
Update: It seems, second recommendation actually worked for this case.
Hope this helps. Thanks.
You need to switch to the iframe firtst then call click() method on the Blue Apply button as follows:
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(#src,'https://apply.indeed.com/indeedapply/resumeapply')]")));
//perfrom other actions
//finally click on Blue Apply button
driver.findElement(By.xpath("//input[#id='apply']")).click();
It seems the index order of the iframes is backwards, at least that's what it looks like to me. I was able to click the "Blue Apply Button" using the following java code:
driver.get("https://ca.indeed.com/cmp/KGHM-International-Ltd./jobs/Financial-Analyst-7a08f1634e7d5c5c");
wait = new WebDriverWait(driver, 10);
//on my screen I had to scroll down to the orange apply button
WebElement applyButton = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("indeed-apply-button")));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", applyButton);
applyButton.click();
Thread.sleep(1000);
driver.switchTo().frame(1);
driver.switchTo().frame(0);
driver.findElement(By.id("applicant.name")).sendKeys("My First Name is");
driver.findElement(By.id("apply-div")).click();
I have a for that with a submit button that looks like this:
<input type="submit" class="btn btn-info pull-right save_button" id="save_button" value="Save"/>
Using JQuery I attach a onclick event to popup a confirmation box:
$('body').on("click", ".save_button", function() {
bootbox.confirm("Do you want these changes to be live in the website?",
function(result) {
if(result) {
$("#editPageForm").parsley().validate();
if( $("#editPageForm").parsley().isValid()) {
$("#editPageForm").submit();
}
}
});
return false;
});
When I test this step by hand everything works fine the form is validated and shows the confirmation box, and after pressing the OK button it saves the content as expect.
But if I use Selenium test I see all the steps going ok, but when the save button is pressed instead of firing this function it just submit the form.
This is the code used to create the driver:
FirefoxProfile profile = new FirefoxProfile();
profile.setEnableNativeEvents(true);
return new FirefoxDriver(profile);
Other Javascript code does work, but I am getting problems with this specific one.
I am using FF44 and selenium drivers I tried 2.48.2, 2.49.1, 2.50 and none of them worked
Did any of you experienced any similar issue?
Thanks
It may be because the page hasn't fully rendered and therefore the click listener hasn't been registered yet. Adding a wait may solve your problem, something like:
WebDriverWait buttonWait = new WebDriverWait(driver, 30L);
buttonWait.until(ExpectedConditions.visibilityOfElementLocated(By.id("someButton")));
HTML code:
<div class="buttonBG">
<input type="button" onclick="window.location.href='?mod=eA&act=00001';" class="buttonGreen" value="TK">
<input type="button" onclick="ttoggle('carianDiv');" class="buttonGreen" value="CK">
</div>
Below is my java code, when I try with below code. Can I know whats wrong is in my selenium webdriver code:
driver.findElement(By.xpath("//input[#class='buttonGreen' and contains(#onclick, 'window.location.href='?mod=eA&act=00001')]")).click();
Try to search by value
driver.findElement(By.cssSelector("[value='TK']")).click();
And for what's wrong, you are searching for ?mod=eA&act=00001 when in the html its
?mod=eA&act=00001
Edit
Another solution is to insert the buttons to list and click by index:
List<WebElement> buttons = driver.findElements(By.className("buttonGreen"));
buttons.get(0).click();
You can also try using explicit wait
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[value='TK']")).click();
This will wait up to 10 seconds for the button to be visible before clicking on it. You can change the selector or time span.
Try using XPath instead of CSS
driver.find_element(By.XPATH, '//input[#onclick=\'window.location.href=\'?mod=eA&act=00001\';\']').click()
Edit
Here is the code to switch to iFrame,
driver.switchTo().frame("frame_name");
NOTE: After completing the operation inside the iframe, you have to again return back to the main window using the following command.
driver.switchTo().defaultContent();
I tried to find a solution to this thing and I spent a lot of time, but it is almost imposible to me to do that.
The matter: I am using Selenium with Java in Firefox. I need to find an element (a listbox) and click on it. So, the code finds the element, but click action does not work. It works fine in Google Chrome every time, and just sometimes in Firefox (with the same Java code sometimes works, and sometimes does not).
There is the part of code with the element when the program enters on the page:
<div id="size-btn" class="size-btn">
<span class="selected-size">SELECCIONA TALLA </span>
<div class="size-select" style="display: none;">
<table>
<tbody>
<tr id="selecsize_2" class="product-size" data-ga-props="{action:'Seleccionar_Producto', opt_label:'Escoger_Talla'}" data-catentryid="1051607">
<tr id="selecsize_3" class="product-size" data-ga-props="{action:'Seleccionar_Producto', opt_label:'Escoger_Talla'}" data-catentryid="1051608">
<tr id="selecsize_4" class="product-size" data-ga-props="{action:'Seleccionar_Producto', opt_label:'Escoger_Talla'}" data-catentryid="1051609">
<tr id="selecsize_5" class="product-size" data-ga-props="{action:'Seleccionar_Producto', opt_label:'Escoger_Talla'}" data-catentryid="1051610">
</tbody>
</table>
<button class="size-guide gaViewEvent gaTrack" data-ga-props="{action:'Seleccionar_Talla', opt_label:'Guia_de_tallas'}" data-href="http://www.anyweb.com/webapp/wcs/stores/servlet/ProductGuideSizeAjaxView?catalogId=24052&categoryId=358056&langId=-5&productId=1047599&storeId=10701">Guía de tallas</button>
</div>
</div>
And there is the part of code that changes when the element is clicked:
<div id="size-btn" class="size-btn opened">
I tried many solutions and sometimes it works, but the next time I run the program, it does not work again.
Some solutions:
It finds the element, but does not run click action. I checked with xpath and cssSelector, and there are unique elements found with those expressions.
driver.findElement(By.xpath("//div[#id='size-btn' and not(contains(#class,'opened'))]/span")).click(); // Also checked with By.cssSelector("span.selected-size")
I though it was because of the time, so I tried to solve it that way.
WebElement we = driver.findElement(By.xpath("//div[#id='size-btn' and not(contains(#class,'opened'))]/span")); // By.cssSelector("span.selected-size")
Thread.sleep(3000);
we.click();
Finally, I was a little bit desperate, and I created a new function to try to do this almost 60 times, looking for the change on the element code and if there was any change, just tried to do click action again.
clickAndWaitWhileElementIsNotPresent(By.xpath("//div[#id='size-btn' and not(contains(#class,'opened'))]/span"),By.xpath("//div[#class='size-btn opened']/span")); // By.cssSelector("span.selected-size")
private void clickAndWaitWhileElementIsNotPresent(By by1, By by2) throws Exception {
for (int second = 0;; second++) {
if (second >= 60)
fail("timeout");
try {
if (isElementPresent(by2))
{
break;
}
else
{
driver.findElement(by1).click();
}
} catch (Exception e) {
}
Thread.sleep(1000);
}
}
There are the images of the element:
Does anybody know how to do that?
Finally I found an answer that works with Firefox as well as Google Chrome.
WebElement we = this.driver.findElement(By.id("size-btn"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", we);
waitForElementPresent(By.xpath("//div[#id='size-btn' and contains(#class,'opened')]/span"));
I am not sure why are you using this Xpath, if you have freedom to change Xpath then record the element using selenium IDE and use Xpath::position from drop down list of target(it picks unique path relative to html header), it will solve problem of dynamic locator. And try below mentioned events.
1- Use clickAt.
2- Use fireevent(focus) and then click. Sometime it happens some element in back ground is getting loaded, when it gets loaded, focus move there hence elementNotVisible error.
3- Use mouseDownRight.
I have the same problem in Firefox. The trick is to click the text inside of not the button itself.
I have some solution, make a class with a robot put there TAB event keys, then call that class. What it does its like a back to focus to the page. For some razon the page lost focus and never find that botton.
Robot robot;
try {
robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
} catch (AWTException e) {e.printStackTrace();}
You can try to use the Actions class from org.openqa.selenium.interactions:
WebElement element = driver.findElement(By.id("size-btn"));
Actions builder = new Actions(driver);
builder.moveToElement(element).click(element);
builder.perform();
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.click(element);
Action action = actions.build();
action.perform();
This worked for me.