Can't select option with Selenium Webdriver - java

I have very strange problem. Using selenium I am writing simple web-bot trying to fill page with data, submit them, and harvest results.
I fill all the forms with no problems at all, but than I have to first enter the ZIP code, than click somewhere else for AJAX to list all the possibilities, than select the appropriate option (I want to always select the first one).
But my problem is, I simply can't select it. I fill the ZIP, click the option list itself, wait to "please select" message to get lost (by this time my choice should be there) and than selecting it. I tried option.click(), I tried selectByVisibleText(), and even the deprecated setSelected(). Nothing happens. All I see in FF is drop-downed list of option, with the first one being marked, but that's all. I tried many ways, with no luck at all.
There is my last-attempt code:
ZIPCode = driver.findElement(By.id("formparam_data2_zip")); //get and fill ZIP
ZIPCode.sendKeys(ZIP);
address = driver.findElement(By.name("formparam_data2_zip_id")); // click to fire AJAX
address.click();
(new WebDriverWait(driver, 20)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) { // wait until AJAX shows results
WebElement elm = d.findElement(By.id("formparam_data2_zip_id"));
List<WebElement> options = elm.findElements(By.tagName("option"));
for(WebElement w : options){
if(w.getText() != "Prosím, vyberte."){
return true;
}}
return false;
}});
List<WebElement> options = address.findElements(By.tagName("option"));
options.get(0).click(); // click first option - ! this failes !
phaseTwoBtn = driver.findElement(By.id("formparam_data2_next")); // than submit...
phaseTwoBtn.submit();

I had a similar problem and had better results using the Actions class and then making sure to use the moveToElement() method before clicking on it.
Actions builder = new Actions(d);
builder.moveToElement(options.get(0)));
builder.click();
builder.build().perform();
The moveToElement method makes sure the element is in the visible window

Using key board keys we can solve this problem in selenium webdriver .Code for the above example,ZIPCode.sendkeys (ZIP);ZIPCode.sendkeys (Keys.Tab);
ZIPCode.sendkeys (Keys.Return);

try this
if(!w.getText().equals("Prosím, vyberte.")){
return true;
}

Related

Selenium Java - Click if element exists, continue with the next command if element not found

i'm trying to create a script to test a web site (js application), code is almost done but i encounter a problem. The script its supposed to edit a question on the website (the question uses a lot of variables from a database) and depending on were the script failed or if anyone else edited the question there is a chance for the script to get a pop-up message(not a separate window or new tab). I want the code to:
Click the element if present or go to the next line of code if the element does not exist.
I tried using but it does not help:
Alert alert = driver.switchTo().alert();
alert.accept();
My code:
driver.findElement(By.xpath("//button[2]")).click();
// Click unselect all
Thread.sleep(1000);
driver.findElement(By.linkText("Romania")).click();
// Select Romania
log.debug("Select Romania");
Thread.sleep(2000);
driver.findElement(By.linkText("Germany")).click();
// Select Germany
log.debug("Select Germany");
Thread.sleep(2000);
driver.findElement(By.xpath("//div[4]/a")).click();
// Click Save Button
log.debug("Click Save");
Thread.sleep(3000);
**driver.findElement(By.xpath("//div[4]/div/div/div/div/div/button")).click();**
// Pop-up message
log.debug("Click Pop-up message");
Thread.sleep(3000);
/////////////// Single Answer
driver.findElement(By.linkText("Change")).click();
// Click Change Template
log.debug("Click Change");
Thread.sleep(2000);
The you can find the line with the issue between **** (pop-up), how can i click if the element exists or move to driver.findElement(By.linkText("Change")).click(); if element not found.
Please let me know if more info is required.
Edit:
To give more details about why the pop-up appears. The script edits a question, the questions have multiple templates and the script is supposed to go through each template after selecting the template the script will associate a variable from the database to the question.
Templates:
Single answer question
Single answer dropdown question
Multiple answer question
Multiple answer dropdown question
Date
The pop-up message appears as a warning (that the variable used will be removed )when the template is changed from multiple answer to single answer/date or the other way around.
In the perfect case if the script finishes successfully (it will end with single answer dropdown - first question is single answer so the pop-up does not appear )and no one edits the question i will not encounter the pop-up but if the script fails due to x reason after changing the template to multiple answer, when i restart the script i will receive that pop-up/warning.
The issue also occurs when changing the language of the question as shown in the code above, i have multiple steps were i encounter this problem.
At the moment in order for the script to run and avoid the problem mentioned above, i need to edit the question myself and select a specific language and template before running the script.
If no matching elements are found, an instance of NoSuchElementException is thrown.
try {
WebElement popUp = driver.findElement(By./**your expression**/);
popUp.click();
} catch(NoSuchElementException | StaleElementReferenceException e) {
log.debug("Impossible to click the pop-up. Reason: " + e.toString());
}
I'd recommend two approaches.
Simply poll the DOM for the pop-up and click the button if exists:
List<WebElement> button = driver.findElements(By.xpath("//div[4]//button"));
if (!button.isEmpty()) {
button.get(0).click();
}
....
driver.findElements() is used to avoid try-catching NoSuchElementException in case using driver.findElement()
You may use explicit wait to wait some time for the button to appear:
try{List<WebElement> button = (new WebDriverWait(driver,10)).until(ExpectedConditions.presenceOfElementsLocated(By.xpath("//div[4]//button")));
if (!button.isEmpty()) {
button.get(0).click();
}
}
catch(TimeoutException e)
{
}

element not visible: Element is not currently visible and may not be manipulated

I'm trying to select one of the element from dropdown.I have retrieved 12 elements when I used the method getAttribute():
Select select = new Select(driver.findElement(By.xpath("//select[#id='dataset_downloadDataset_select']")));
List<WebElement> options = select.getOptions();
System.out.println(options.size());
for (int i=1; i<=11; i++){
System.out.println(options.get(i).getAttribute("value"));
After retrieving 12 elements of dropdowm,I want to select one of them.For that I have tried Actions/Javascriptexecutor but I'm getting element not visible exception.The code used for Action method is:
WebElement mnuElement;
WebElement submnuElement;
mnuElement = driver.findElement(By.xpath("//input[starts-with(#data-activates,'sele')][#value='XXXXXXXXXXX']"));
submnuElement = driver.findElement(By.xpath("//*[#id='dataset_downloadDataset_select']/option[4]"));
Actions builder = new Actions(driver);
builder.moveToElement(mnuElement).perform();
Thread.sleep(5000);
driver.findElement(By.xpath("//*[#id='dataset_downloadDataset_select']/option[4]")).click();
Could anyone help me to resolve this.
It depends on browser you are using. Chrome can click option without extending while firefox can't deal with it. Use select to choose from . Option you are using requires to click on the list and then choose, but it is simplier to do like that
Code for firefox (and probably every browser)
WebDriver driver;//then choosing browser
element=driver.findElement(By.xpath("//select[#id='dataset_downloadDataset_select']"));//or whatever
Select select=new Select(element);
//To select what you want, this is selecting, nothing more
select.selectByValue("Mainframe File 1");//or other

Selenium - Text entered in same field, even though intended to type in different fields

Using selenium, when trying to enter username and password in login form, sometimes the text is entered on the same field. Username and password are having unique identifier.
For sending keys, the following steps are done.
sendKeys(By.id("login_username"), "abc");
sendKeys(By.id("login_password"), "efg");
public void sendKeys(By locator, String text) {
WebElement element = findElement(locator);
if(element != null) {
element.clear();
element.sendKeys();
}
}
public WebElement findElement(By locator) {
return wait(org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated(locator));
}
public WebElement wait(ExpectedCondition<WebElement> condition) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).pollingEvery(1, TimeUnit.SECONDS)
.withTimeout(60, TimeUnit.SECONDS)
.ignoreAll(Arrays.asList(NoSuchElementException.class, TimeoutException.class));
return wait.until(condition);
}
But somehow, when entering text, both the username and password texts are getting typed onto the password field. This is not happening always though. Not able to understand what could possibly go wrong or what to check. Any suggestions...
platform: Ubuntu 16.04.1 LTS 64-bit
chromedriver version: 2.25
chrome browser version: 55.0.2883.87
Thanks in advance.
The sendKeys() action performs the following steps:
Gets the coordinates of the element
Clicks at the coordinates it got (using a mouse action)
"Types" the text (that will be received by whatever element is currently focused)
It can go wrong if the element can't be focused when starting the action (because it's disabled for example), or if the coordinates change between getting the coordinates and clicking/focusing the element (because the layout is still changing).
Another common cause can be onClick action hooked on the element, that can lead to race conditions. Without seeing the actual page, it is possible that after selenium clicks, an onClick action is still working when the text is being typed. This basically looks like this:
Selenium clicks
onClick action starts (element might get focused only after it finishes)
Selenium starts typing (onClick haven't
returned yet, so the wrong elements gets the text)
the onClick
action finishes, but by that time Selenium finished too.
As a solution you can try focusing the element directly, and wait until it is really focused before sending the keys. This question might be of use for this case.

Unable to set focus on pop up

[![enter image description here][1]][1]HTML code is shown in Screenshot [![enter image description here][2]][2]
I tried with Action class
WebElement element = InspectationOrder.wd.findElement(By.xpath("//div[#class='qx-window']"));
Actions actions = new Actions(InspectationOrder.wd);
actions.moveToElement(element).click().build().perform();
but found "java.lang.NullPointerException" while i tried to move focus.
but same action code works for other area in application
Also tried with
for (String popup : wd.getWindowHandles())
{
wd.switchTo().window(popup);
}
but not working :(
May be issue with z-index but m don't have more idea about the same .
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
boolean bool = (Boolean) ((JavascriptExecutor)d).executeScript("return $('.modal').is(':visible') ");
return bool;
}
});
Your Dialog is actually an div in an upper layer. This codes waits up to 10 seconds until the dialog is created and show completely. Inside JavaScript is used to select the dialog and check weather is visible or not. (display: none). The result is returned. If the result is false your test will stop.
Can you please try adding an id to the div and use the below code?
driver.switchTo().frame(driver.findElement(By.id(id)));
driver.findElement(By.id(id inside popup));
Selenium latest version(Selenium 3 with GeckDriver ) automatically handles set focus.
Previously I am using selenium 2 in which we have to setfocus on new element.But in selenium 3 with GecoDriver we have no need to worry about small popups.
In my whole automation script selenium 3 handles setfocus[ Not fully but at basic level ] for me and works form me.
Use full links.
LINK-1
[LINK-2]
-Thanks
Dhaval

selenium, how can I select new window

I run my selenium rc test in Eclipse with TestNG. I have a link which tries to open a new browser page. How can I select this new page to operate in? I use this code:
selenium.selectWindow("name=NewPage");
however it says page not found. I also try to define page ids or titles with this code:
String[] wins = selenium.getAllWindowIds();
for (String s : wins)
System.out.println("win: " + s);
It does not define my new opened window:
win: MainPage
win:
If use selenium.getAllWindowNames() I get win: selenium_main_app_window
win: selenium_blank65815.
I write this code selenium.selectWindow("name=blank99157"); but get the error - ERROR: Window does not exist. If this looks like a Selenium bug, make sure to read http://seleniumhq.org/docs/02_selenium_ide.html#alerts-popups-and-multiple-windows for potential workarounds.
The window obviously has no name, so you can't select it by name.
If the window is opened via JavaScript and you can change the script, try changing window.open("someUrl"); to window.open("someUrl", "someName");, you'll be then able to select the window by the set name. More information on the MDN doc for window.open().
Selenium RC doesn't support <a href="someUrl" target="_blank"> links (which open the link in a new window). Therefore, if the window is opened by a link of this type, you have to find this <a> element, get the href attribute and call
selenium.openWindow(theFoundUrl, "theNewWindow");
selenium.selectWindow("id=theNewWindow");
If it is opened via JavaScript before or during the onload event, you'll need to call
selenium.openWindow("", "theNewWindow");
selenium.selectWindow("id=theNewWindow");
More information on this in the bug SEL-339 or in the openWindow() and selectWindow() JavaDocs.
If you have only two windows / want to open the newest one, you can try
selenium.selectPopup()
That is, obviously, the easiest way, because it selects the first non-top window. Therefore, it's only useful when you want to select the newest popup.
If the new window has a unique title, you can do
selenium.selectPopup("Title of the window");
or selenium.selectWindow("title=Title of the window");
Otherwise, you must iterate over selenium.getAllWindowNames() to get the right name (Selenium creates names for windows without one). However, you can't hardcode that name into your testcase, because it will change every time, so you'll need to work out some dynamic logic for this.
You won't like this: Go for WebDriver. It should be far more resistant to such problems.
WebDriver driver = new FirefoxDriver();
WebElement inputhandler = driver.findelement(By.linktext("whatever here"));
inputhandler.click();
String parentHandle = driver.getWindowHandle();
Set<String> PopHandle = driver.getWindowHandles();
Iterator<String> it = PopHandle.iterator();
String ChildHandle = "";
while(it.hasNext())
{
if (it.next() != parentHandle)
{
ChildHandle = it.next().toString();
// because the new window will be the last one opened
}
}
driver.switchTo().window(ChildHandle);
WebDriverWait wait1 = new WebDriverWait(driver,30);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.id("something on page")));
// do whatever you want to do in the page here
driver.close();
driver.switchTo().window(parentHandle);
You might not be using the correct window ID.
Check out this link. You might find your answer here.
Let me know you this helps.
Try selenium.getAllWindowNames(), selenium.getAllWindowTitles()..one of them will work for sure.

Categories

Resources