if I execute the following code in FireFoxDriver:
WebElement element = driver.findElements(By.id("some_id")); // element being a textbox
element.sendKeys("apple");
element.sendKeys(Keys.RETURN);
The sendKeys(Keys.RETURN) is not performing its desired function.
Actually what I am trying to do is Input a text in a dynamic text search box (like one in facebook search) and press enter. The input is working fine but not the enter key.
sendKeys("apple") works, even sendKeys(Keys.BACK_SPACE) works, but not Keys.RETURN.
Does anyone have ideas? Thanks guys!
Not exactly sure why this happens, but there are a couple alternate ways of doing this that may help:
If elements are in a form, and there is no javascript that runs on submit or something you can use .submit() on any form input element, such as inputs and textareas:
WebElement element = driver.findElements(By.id("some_id"));
element.sendKeys("apple");
element.submit()
You can send the newline character with your input:
WebElement element = driver.findElements(By.id("some_id"));
element.sendKeys("apple\n");
Provide send_keys a list:
WebElement element = driver.findElements(By.id("some_id"));
element.sendKeys("apple", Keys.ENTER);
Got the solution to the above problem. U just need to add, a delay.
This happens because the Java Class runs too fast, so if u have sent a call, and pressed enter/ tab, before the element arrives, the enter is pressed, that is why this doesn't work. Just add Thread.delay(1000); before your Keys.RETURN command. That will do.
Worked for me.
I tried sending \n and fiddled with various commands until I found someone explaining that "keyPress (target) 13" will send the return key.
So first I use type to enter the string I want ...
*
*<tr>
<td>type</td>
<td>id=status</td>
<td>This is my test string</td>
</tr>*
*
... and then send the Enter key to the same text input box
*
*<tr>
<td>keyPress</td>
<td>id=status</td>
<td>13</td>
</tr>*
*
Related
Im trying to get into java/selenium but i have some problems i cant solve.
I cant interact with the "WEITER" Button from the website Snipes.com (https://www.snipes.com/checkout?stage=payment#payment). It works with every other button but the box of this one looks a little bigger than the button itself. Perhaps this is the problem but i dont know how i can only click the button.
The code im using for this part is following:
TimeUnit.MILLISECONDS.sleep(500); //select Paypal as Payment
selectPayment = driver.findElementByXPath("/html/body/div[3]/div[2]/div/div/div[2]/div[1]/div[3]/div[2]/div/div/form/div/ul/li[1]/div[1]/label");
js.executeScript("arguments[0].scrollIntoView(true);", selectPayment);
js.executeScript("arguments[0].click();", selectPayment);
TimeUnit.MILLISECONDS.sleep(500);
nextButtonCheckout = driver.findElementByXPath("/html/body/div[3]/div[2]/div/div/div[2]/div[1]/div[3]/div[2]/button");
nextButtonCheckout.click(); //click the "WEITER" Button
TimeUnit.MILLISECONDS.sleep(200);
Is there any way to click only the "main" button element instead of the whole thing so i can interact with it?
Error: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[5]/div/div/div/div/div1/button"}
whole error: https://pastebin.com/jki8T8Y4
I want to click the little "x" on the top right of this pop up and sometimes it works but sometimes it doesnt. How can I test if it found the element and if not try again? I use proxies for this and the speeds are different so i cant just wait 5s and then check if it works. Sometimes the element can be found in 2s sometimes in 15s. I need to retry it a few times and my idea is to check it the variable 'selectRegion' if something is stored in it. I tried it with if(selectRegion =! "the output from the element") but i cant compare a WebElement with a String.
the code i use:
//Snipes Region + accept cookies
driver.get("https://www.snipes.com/login");
TimeUnit.SECONDS.sleep(7);
selectRegion = driver.findElementByXPath("/html/body/div[5]/div/div/div/div/div[1]/button");
selectRegion.click(); //click on the "x"
System.out.println(selectRegion); //get the variable output the use it later for the retries
acceptCookies = driver.findElementByXPath("/html/body/div[2]/div[2]/div/div[2]/div[2]/button");
acceptCookies.click();
This is a common problem but does anyone know how i can use user:passw authenticated proxies with selenium? Everytime i start it there is this authentication pop up but i cant interact with it.
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);
}
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
I want to mimic Enter being pressed in Webtest. I am using Selenium 2.3.1. I want to do it using WebDriver. I know that we can do this using Selenium RC, but I do not want to do it that way. Has anybody done this before? I am open to upgrade to Selenium 2.20.0 (latest).
You can send an Enter key to an element. However, you can't press Enter to, say, confirm a download dialog.
WebElement elem = driver.findElement(By.id("damnit")); // obtain an element
elem.sendKeys(org.openqa.selenium.Keys.ENTER); // this sends an Enter key to the element
elem.sendKeys("hey" + org.openqa.selenium.Keys.ENTER); // this writes and then confirms by Enter