I need to check a checkbox to type values to an input field.
The field appears when i check the box. So i tried :
WebElement box = driver.findElement(By.id("Checkbox_input"));
box.click();
sleep(5);
// the input can't be detected
// so it throw a noSuchElement.
WebElement input = driver.findElement(By.id("PaymentAmount_input"));
input.sendKeys("12345");
I've already use the isSelected() (right after the click()) to verify if it's checked.
Assert.assertTrue(box.isSelected());
I've found something weird that works.. I write that after the ePrepayment.click();
box.submit();
It works because submit() looks like a refresh, so my input appears, but it doesn't delete all values in the others input.
Specs
sleep() method
protected void sleep(int i) {
driver.manage().timeouts().implicitlyWait(i, TimeUnit.SECONDS);
}
Question :
Is there a better way to do that instead of a nasty submit() on a checkbox ?
Thank you, Marco
Share your element HTML if possible. There might be something like onsubmit show input field instead of onclick event.
Your sleep() method doesn't makes sense, since that is a incorrect use of the the Implicit Waits. A more correct approach would be using Explicit Waits:
WebElement box = driver.findElement(By.id("Checkbox_input"));
box.click();
wait.until(ExpectedConditions.visibilityOfElemementLocated(By.id("PaymentAmount_input")));
WebElement input = driver.findElement(By.id("PaymentAmount_input"));
input.sendKeys("12345");
Assuming wait is already correctly started somewhere like:
WebDriverWait wait = new WebDriverWait(driver, 5);
Related
I made a pretty simple selenium test, where I want to open web page, clear field value, start entering text for this field, select first value from the hint drop down.
Web site is aviasales.com (I just found some site with a lot of controls, this is not an advertisement)
I did
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).clear();
and it was working perfectly, I also checked via console that this is the only one object on a page like:
document.getElementById('flights-origin-prepop-whitelabel_en')
So, in next line I'm sending value:
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).sendKeys("LAX");
but it send LAX value for both "flights-origin-prepop-whitelabel_en" and "flights-destination-prepop-whitelabel_en" for some reason, then i tried
DriverFactory.getDriver().findElement(By.id("//input[#id='flights-destination-prepop-whitelabel_en'][#placeholder='Destination']")).sendKeys(destinationAirport);
but I got the same result:
What could be a reason and how to fix this?
Thank you!
Yep... there's some weird behavior going on there. The site is copying whatever is entered into the first field into the second for reason I don't understand. I gave up trying to understand it and found a way around it.
Whenever I write code that I know I'm going to reuse, I put them into functions. Here's the script code
driver.navigate().to(url);
setOrigin("LAX");
setDestination("DFW");
...and since you are likely to use these repeatedly, the support functions.
public static void setOrigin(String origin)
{
WebElement e = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(origin);
e.sendKeys(Keys.TAB);
}
public static void setDestination(String dest)
{
WebElement e = driver.findElement(By.id("flights-destination-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(dest);
e.sendKeys(Keys.TAB);
}
You can see the functions but basically I click in the field, clear the text (because usually there's something already in there), send the text, and then press to move out of the field and choose the default (first choice).
The reason of your issue is the ORIGIN and DESTINATION inputbox binded keyboard event which used to supply an autocomplete list according to your typed characters.
The binded keyborad event breaks the normal sendKeys() functionality. I met similar case in my projects and questions on StackOverFlow.
I tried input 'GSO' into DESTINATION by sendKeys('GSO'), but I get 'GGSSOO' on page after the sendKeys() complete.
To resolve your problem, we can't use sendKeys(), we have to use executeScript() to set the value by javascript in backgroud. But executeScript() won't fire keyborad event so you won't get the autocomplete list. So we need find out a way to fire keyborady event after set value by javascript.
Below code snippet worked on chrome when i tested on aviasales.com:
private void inputAirport(WebElement targetEle, String city) {
String script = "arguments[0].value = arguments[1]";
// set value by javascript in background
((JavascriptExecutor) driver).executeScript(script, targetEle, city + "6");
// wait 1s
Thread.sleep(1000);
// press backspace key to delete the last character to fire keyborad event
targetEle.sendKeys(Keys.BACK_SPACE);
// wait 2s to wait autocomplete list pop-up
Thread.sleep(2000);
// choose the first item of autocomplete list
driver.findElement(By.cssSelector("ul.mewtwo-autocomplete-list > li:nth-child(1)")).click();
}
public void inputOrigin(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
return inputAirport(target, city);
}
public void inputDestination(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepopflights-destination-prepop-whitelabel_en"));
return inputAirport(target, city);
}
I have some tests which click on a tab, however the click is not always performed.
The xpath is correct as most of the times the test works
It is not a timing issue as I ve used thread.sleep() and other methods to ensure that the element is visible before clicking
The test believes that it is performing the click as it is not throwing an ElementNotFoundException or any other exceptions when 'performing' the click. The test fails later on after the click since the tab content would not have changed.
Further Info
I am using Selenium 2.44.0 to implement tests in Java which run on Chrome 44.0.2403.107 m.
Is there something else that I can do or could this be an issue with selenium?
There are several things you can try:
an Explicit elementToBeClickable Wait:
WebDriverWait wait = new WebDriverWait(webDriver, 10);
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("myid")));
button.click()
move to element before making a click:
Actions actions = new Actions(driver);
actions.moveToElement(button).click().build().perform();
make the click via javascript:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", button);
you can go with linkText if the tab name contains any unique string. And make sure your tab is not dynamic. It should be visible in source code(manual source code(ctrl+u)).
The following method work for me
WebElement button = SeleniumTools.findVisibleElement(By.cssSelector("#cssid"));
Actions actions = new Actions(driver);
actions.moveToElement(button).click().build().perform();
I have a similar problem. Tried all solutions from the top answer. Sometimes they work, sometimes don't.
But running code in an infinite loop works always.
For example, we need to click on element-two which is not visible until element-one is clicked.
WebDriverWait wait = new WebDriverWait(webDriver, 10);
while (true){
try {
WebElement elementOne =
wait.until(ExpectedConditions.elementToBeClickable(By.id("element-one")));
elementOne.click();
WebElement elementTwo =
wait.until(ExpectedConditions.elementToBeClickable(By.id("element-two")));
elementTwo.click();
break;
} catch (Exception e){
//log
}
}
I have a similar problem. Here is my solution:
table_button = driver.find_element(By.XPATH, insert your xpath)
try:
WebDriverWait(driver, 15).until(EC.element_to_be_clickable(table_button)).click()
except WebDriverException as e:
print('failed')
print(e)
Through code above, you can find the error message if your button is not clickable.
For example, my error message is 'nosuchelement' and 'clcik is not clickable', then I got back to check the table_button.accessible_name, found it print a 'null' value, so that means my XPATH is incorrect.
I am using Webdriver in Java and I encountered an issue repeatedly that I can't find a proper solution yet.
It is to do with doing actions on a page that will cause this page DOM to change (for example, Javascript lightbox), then my JUnit test is expecting new elements after the DOM change but my test is getting the old DOM element.
To give you an example, I have a scenario as below.
First of all click “Add item” button in the below image and the light box appears:
Then fill in all the item details and click "Add & Close". You will see the screen below:
Notice that now there is an info message Your item ... has been added.
Now I put keywords in the Search text box and hit enter and the info message will be changed to below:
In my JUnit test, the flow is like below:
....
itemDetailsPage.clickAddAndClose();
itemDetailsPage.searchItemBy("Electricity");
assertEquals("Your search for 'electricity' returned 2 results.",
itemDetailsPage.getInfoMsg());
....
Now this test is not very robust, because if the network is slow, most of the times, getInfoMsg() will return the previous info message Your item ... has been added instead of the latest info message, which causes the test to fail. Just a side note that these two info message have share the same html element id.
The solution I am trying to implement here are:
add explicit wait in clickAddAndClose()
So it looks something like:
public void clickAddAndClose() {
...
clickWhenReady(driver, By.id(addAndCloseButtonId));
...
waitForElementByLocator(driver,By.id(itemInfoMsgId),10);
}
The second wait proves to be useless because, itemInfoMsgId already exist when the user added the item from the add item lightbox.
add waitForPageLoaded() method at the end of clickAddAndClose() to try to wait for the page to finish reloading. The generic method for waitForPageLoaded() below:
public void waitForPageLoaded(WebDriver driver) {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript(
"return document.readyState").equals("complete");
}
};
Wait<WebDriver> wait = new WebDriverWait(driver, 30);
try {
wait.until(expectation);
} catch (Throwable error) {
assertFalse("Timeout waiting for Page Load Request to complete.",
true);
}
}
I am expect at the end of clickAddAndClose(), it will see this page is still being updated so it will wait until the info message has been updated. But this does not seem to work either.
That leaves me to the last choice will is to add a thread sleep at the end of clickAddAndClose(). I want to avoid using it.
Is there a generic way of solving this kind of problem? How do I detect that the page DOM is still changing and tell Webdriver to wait until it finishes refreshing?
Waiting for the page to be loaded won't work if (as it seems to be the case) your page is being modified by AJAX operations.
Instead of waiting for the page to load, wait for the condition you are testing to become true. This way, you give the AJAX operation time to execute and if your there is a problem you will get an error when the time out occurs.
I usually use the Python bindings for Selenium and it has been quite a while since I wrote Java code but I believe it would look something like this, with X being replaced with a type appropriate for the itemDetailsPage object:
new FluentWait<X>(itemDetailsPage)
.until(new Function<X, Boolean>() {
public Boolean apply(X itemDetailsPage) {
return "Your search for 'electricity' returned 2 results." == itemDetailsPage.getInfoMsg();
};
});
Seems like you need to wait until ajax has finished its job. In a similar situation I've used a method similar to waitForJQueryProcessing described here. Take a look, it might help.
The button type is image, and the relevant code in HTML code attached. I have entered all the data and clicked on Apply Now button, it is not at all saving. But when I try to create it manually, it is saved in less than 15 seconds.
Please find the attached screen shot.
The relevant code for the same:
//Navigating to Quick Application
driver.get(QAurl);
Thread.sleep(15000);
driver.findElement(By.id("DdlSalesPerson")).sendKeys("Swamy m Kumara");
driver.findElement(By.id("TxtFName")).sendKeys("Kumar");
driver.findElement(By.id("TxtLName")).sendKeys("Swamy");
driver.findElement(By.id("TxtAddress")).sendKeys("434, Main Road, Somajiguda");
driver.findElement(By.id("TxtZip")).sendKeys("79081");
driver.findElement(By.id("TxtSSN1")).sendKeys("881");
Thread.sleep(15000);
driver.findElement(By.id("TxtSSN2")).sendKeys("72");
driver.findElement(By.id("TxtSSN3")).sendKeys("4365");
Thread.sleep(5000);
driver.findElement(By.id("TxtDayPhone1")).sendKeys("963");
driver.findElement(By.id("TxtDayPhone2")).sendKeys("210");
driver.findElement(By.id("TxtDayPhone3")).sendKeys("5478");
Thread.sleep(5000);
driver.findElement(By.id("ChkIAgree")).click();
driver.findElement(By.id("TxtSignature")).sendKeys("Kumar Swamy");
Thread.sleep(5000);
System.out.println("Entered all the required fields");
//Reading the value in the image.
WebElement element = driver.findElement(By.id(OR.getProperty("FP_SImg_ID")));
String src = ((JavascriptExecutor)driver).executeScript("return arguments[0].attributes['src'].value;", element).toString();
img =src.split("=");
System.out.println("Value retrieved from the Image source: "+img[1]);
driver.findElement(By.id(OR.getProperty("FP_TxtSImg_ID"))).sendKeys(img[1]);
Thread.sleep(5000);
driver.findElement(By.id("TxtEmailId")).sendKeys("abc#abc.com");
driver.findElement(By.name("BtnSubmit")).click();
Thread.sleep(35000);
System.out.println("Successfully Applied from the QuickApp");
HTML code for the Apply now button:
<input id="BtnSubmit" type="image" style="height:33px;width:121px;border-width:0px;"
onclick="javascript:return validateControls();" src="../Common/Images/HybridQA
/apply_now.png" title="Submit Here" tabindex="45" name="BtnSubmit">
Any help will be appreciated.
You have 1 minute 25 seconds of Thread.sleep() in your code...
Remove all the thread.sleep(), if you are waiting for elements to appear do it properly, use an explicit wait:
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
To take an example from the page linked above:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
Have a look at the ExpectedConditions class to see the available conditions built into selenium, if they don't meet your needs it's trivial to write your own expected conditions.
-------------------Edit-------------------
For the record this answer is for the original question that was asked which is quoted below (you can have a look at the edit history of the original question to verify this as well).
Taking long time to save after clicking on Apply Now button using Webdriver in Java
Taking long time to save after clicking on Apply Now button using
Webdriver in Java. I have entered all the data and clicked on Apply
now button, it is not at all saving. But when i try to create it
manually, it is saved in less than 15 seconds. Please find the
attached screen shot.
There could be 2 reasons for this problem.
One is from the HTML code of 'Apply Now' button, I could see that it shows as "input
id='BtnSubmit'", but in your script its written as
'driver.findElement(By.name("BtnSubmit")).click();'.
Shouldn't it be "driver.findElement(By.id("BtnSubmit")).click()"?; 'name' must be
replaced with 'id'.
At the end of the script you click 'BtnSubmit', the session might expire immediately after
you click that button. This problem usually occurs when you use an older and new version
of selenium standalone jar file. See to that you use only the latest version and not in
addition to an old version.
Use this,
driver.findElement(By.id("TxtEmailId")).sendKeys(Keys.ENTER);
after this,
driver.findElement(By.id("TxtEmailId")).sendKeys("abc#abc.com");
and comment,
driver.findElement(By.name("BtnSubmit")).click();
So your code looks like,
driver.findElement(By.id("TxtEmailId")).sendKeys("abc#abc.com");
driver.findElement(By.id("TxtEmailId")).sendKeys(Keys.ENTER);
//driver.findElement(By.name("BtnSubmit")).click();
Sometimes it's difficult to handle image buttons because these buttons are activated when all required fields are entered. Make sure you filled all mandatory fields and press enter after entering last field in the form. First try to do it manually. Instead of clicking on button press enter at last input field and use same stratefy with automation.
Update:
Use your own code and replace Thread.sleep() with below method.
Call it like,
waitForElementToBePresent(By.id("DdlSalesPerson"), 15000);
It waits for next element whichever you pass as argument. It returns true if found or false if not. If element found within the given time it will return true immediately instead of waiting for given time.
public boolean waitForElementToBePresent(By by, int waitInMilliSeconds) throws Exception
{
WebDriver driver = getDriver();
int wait = waitInMilliSeconds;
int iterations = (wait/250);
long startmilliSec = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
if((System.currentTimeMillis()-startmilliSec)>wait)
return false;
List<WebElement> elements = driver.findElements(by);
if (elements != null && elements.size() > 0)
return true;
Thread.sleep(250);
}
return false;
}
i'm currently testing the GUI of my application, and i wanted to know if it's possible to set the focus to a WebElement ?
I'm using Selenium 2.0 and the webdriver.
So i'm looking for something like that : driver.findElement(xxxx).setfocus();
Thank you.
EDIT :
I've alreardy tested that kind of tricky things
// getting the element WebElement
eSupplierSuggest = driver.findElement(By.xpath("..."));
//get le location and click
Point location = eSupplierSuggest.getLocation();
new Actions(driver).moveToElement(eSupplierSuggest, location.x, location.y).click();
//or
//directly perform
new Actions(driver).moveToElement(eSupplierSuggest).click().perform();
i red somewhere that the click focus the element, but in my case, nothing works. lol
PS : this is a sub-question of that original post Click on a suggestbox, webdriver
I normally send an empty key to the element so it gets focused. So for example:
element.send_keys ""
In order to set focus on the element you can use executeScript method as described below :
JavascriptExecutor js;
js.executeScript ("document.getElementById('x').focus()");
Once the focus is set you can easily use send_keys provided by webdriver api.
Try using cssSelector for the autosuggestion click as shown below and let me know if you are still facing the issue.
// supplier ops, i find and type data into the input
WebElement eSupplier = driver.findElement(By.id("supplier:supplierOps_input"));
eSupplier.sendKeys("OPS1");
sleep(5); // wait the suggestbox
// i find the suggestbox
WebElement eSupplierSuggest = driver.findElement(By.cssSelector("css path of that specific value in the auto suggestion box"));
eSupplierSuggest.click();
sleep(5); // wait the refresh for the next field supplierAddress
There is no function in the WebDriver API to set focus on an element.
If you want to do it you would have to write some JavaScript to set focus and then use a JavaScriptExecutor to run the JavaScript.
Make sure, that you are not changing the frame....
Other wise .click() should do the trick