Getting Java Webdriver 'Down Arrow' action to work - java

So I have been trying to resolve this for several hours. I have no clue what I am doing wrong.
This is a type ahead field I am looking in is <input type="text" id="id_attendees" name="attendees">. When I type in there a js dropdown is created. When I press the Down Arrow on keyboard it works fine and selects the top choice. When I do keyDown --- id=id_attendees --- \40 in IDE it works fine and also selects the choice.
I cannot get it to do the same in Java webdriver though
Actions actionObject = new Actions(driver);
actionObject.sendKeys(Keys.ARROW_DOWN);
^doesn't work.
driver.findElement(By.id("id_attendees")).sendKeys(Keys.ARROW_DOWN);
^doesn't work
I tried Keys.DOWN in both cases, that doesn't work either. I created a literal String altm = "\u0040"; and all that does is type an # symbol.
I also tried a bunch of other things as well and nothing is working. I have no clue what am I missing.
EDIT 1:
#Roddy Thank you! - Given that link I added the following that did work (after importing DefaultSelenium and WebDriverBackedSelenium.
DefaultSelenium sel = new WebDriverBackedSelenium(driver,vars.siteurl);
sel.fireEvent("//input[#id='id_attendees']", "keydown");
EDIT 2:
--> DOH that doesn't work. I got overzealous apparently.

some time scripts takes some time to load the list so need to add wait,
WebElement ar=driver.findElement(By.id("id_attendees"));
Thread.sleep(1000);
ar.sendKeys(Keys.ARROW_DOWN);

I think your use of Actions is not quite right.
The implementation is a builder pattern. Calling sendKeys doesn't send the event, it only stages the event to be fired when you call perform. Note that the return value of sendKeys is an Actions instance.
Actions actionObject = new Actions(driver);
actionObject = actionObject.sendKeys(Keys.ARROW_DOWN); //ASSIGN the return or you lose this event.
actionObject.perform(); //Should do what you want. Note that this will reset the builder.
Hope that helps.

With Actions class, after defining what it will do for you, you need to first build() it. So in your case it would be like this:
Actions actionObject = new Actions(driver);
actionObject.sendKeys(Keys.ARROW_DOWN).build();
When you want your script to execute that action, you need to perform() it. You can chain it right after your build() method (if you are using it just once, for example) or later in your code whenever you need it, like this:
actionObject.sendKeys(Keys.ARROW_DOWN).build().perform();
OR
actionObject.perform();
Good luck!

Related

How to select a option from drop down with div tag/class?.selenium

I have tried all the possible things. also, tried searching over tried different combinations and variations. I can get the element clicked which opens the dropdown. but i am not able to select an option in it. I tried with actions, sendkeys, keys.down/enter and multiple things as well. however, it didn't help. That's the only thing I am stuck on.
//selecting office
1.driver.findElement(By.id("DG5QEPn")).click();
Actions actions = new Actions(driver); actions.moveToElement(driver.findElement(By.xpath("//*[#id="DG5QEPn"]/div/div/div1/div1"))).click();
driver.findElement(By.id("DG5QEPn")).click();
driver.findElement(By.id("DG5QEPn")).sendKeys("RTP HQ"); driver.findElement(By.id("DG5QEPn")).sendKeys(Keys.Down); driver.findElement(By.id("DG5QEPn")).sendKeys(Keys.Enter);
Html-
In the below image.
You should enumerate through all of the options then click on the one you want. Take a look at this.
EDIT
The easiest way that I have found was to do something along the lines of:
el = driver.find_element_by_id('id_of_select')
for option in el.find_elements_by_tag_name('option'):
if option.text == 'The Options I Am Looking For':
option.click() # select() in earlier versions of webdriver
break
Below code worked for me
WebElement selectMyElement = driver.findElement(this.getObject(By.Id("Id of Your DropDown")));
selectMyElement.click();
Actions keyDown = new Actions(driver);
keyDown.sendKeys(Keys.chord(Keys.DOWN, Keys.DOWN, Keys.ENTER)).perform();

moveToElement mouse hovering function in Selenium WebDriver using Java not stable

I'm using Selenium 3.0.1 for running automation tests using TestNG.
In one test I'm trying to hover on an action menu and then click an option in that menu:
Actions builder = new Actions(getWebDriver());
builder.moveToElement(actionButton).build().perform();
But the test is not stable. I can see the menu opens but immediately closing, so the test fails because it's not finding the option any more.
I'm receiving this error:
java.lang.IllegalArgumentException: Must provide a location for a move action.
at org.openqa.selenium.interactions.MoveMouseAction.<init>(MoveMouseAction.java:30)
at org.openqa.selenium.interactions.Actions.moveToElement(Actions.java:251)
How can I check if the menu is open? the perform() method is returning void.
I notice if I put call the moveToElement twice, than the test is being more stable. Is there any elegant option of doing so?
Actions builder = new Actions(getWebDriver());
builder.moveToElement(actionButton).build().perform();
builder.moveToElement(actionButton).build().perform();
This how the menu looks like when we hover over it:
I find this issue:
https://sqa.stackexchange.com/questions/3467/issue-with-losing-focus-of-hover-command-when-the-mouse-is-outside-of-the-acti
which explains best my problem. unfortunately, still with no solution.
If it is not necessary for you to open the menu, please try clicking the option using JavascriptExecutor. JavascriptExecutor can click a hidden element as well, all that is necessary for the click to be triggered using JavascriptExecutor is that the element is present on the DOM.
Snippet (Java):
((JavascriptExecutor)driver).executeScript("arguments[0].click()", driver.findElement(By.cssSelector("hiddenOptionFromMenu")));
You can wait for the menu to appear after the hover with a FluentWait, like so:
FluentWait<> wait = new FluentWait<>(getWebDriver())
.withTimeout(driverTimeoutSeconds, TimeUnit.SECONDS)
.pollingEvery(500, TimeUnit.MILLISECONDS)
.ignoring(StaleElementReferenceException.class)
.ignoring(NoSuchElementException.class)
.ignoring(ElementNotVisibleException.class)
wait.until(x -> { return driver.findElement(menuElementBy); } );
If the mouse hover succeeded - the menu starts appearing - there's no reason you need to call it twice.
It seems like a timing issue.
If the menu has a transition effect, then add a delay of the duration of the effect:
new Actions(driver)
.moveToElement(menu)
.pause(100) // duration of the transition effect in ms
.perform();
submenu.click();
You could also wait for the targeted element to become visible and steady (same position returned twice in a row).

Webdriver test doesn't select option from dropdown

i have a registration form for checkout,I have to select a state from drop down,for which i have written a script:
WebElement wb = driver.findElement(By.name("user_data[s_state]")) ;
Select selwb = new Select(wb) ;
selwb.selectByValue("KR");
driver.findElement(By.name("dispatch[checkout.update_steps]")).click() ;
but after executing this script,it is not selecting given value from dropdown.hence i am unable to proceed on next step. Plz help me out....
I can give you a suggestion since I have worked with Selenium webdriver for sometime. The webdriver executes very fastly. Selenium driver doesnt take care whether the page loaded or not. So I recommend you to add code just before the click/selection events to make sure that the page loaded completely. There are options like waitForPageLoad() or checkifComponent exist to make sure that page is loaded properly before the events are triggered. Hope this will help you.
If any wait doesn't help - like suggested before - try to select eg. by index or text.
I've had such wired cases where one of ByValue/ByText/ByIndex method didn't work although others did with particular dropdown.
If you are about to select the drop down use the following:
First make the webdriver wait
Then try choosing the element with the help of
driver.findElement(By.xpath("xpath of the value").select
OR
you can use like the following:
new WebDriverWait(driver,30).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("the xpath of the value"))).click();

Set focus on WebElement?

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

selecting pulldown in htmlunit

I am using htmlunit in jython and am having trouble selecting a pull down link. The page I am going to has a table with other ajax links, and I can click on them and move around and it seems okay but I can't seem to figure out how to click on a pulldown menu that allows for more links on the page(this pulldown affects the ajax table so its not redirecting me or anything).
Here's my code:
selectField1 = page.getElementById("pageNumSelection")
options2 = selectField1.getOptions()
theOption3 = options2[4]
This gets the option I want, I verify its right. so I select it:
MoreOnPage = selectField1.setSelectedAttribute(theOption3, True)
and I am stuck here(not sure if selecting it works or not because I don't get any message, but I'm not sure what to do next. How do I refresh the page to see the larger list? When clicking on links all you have to do is find the link and then select linkNameVariable.click() into a variable and it works. but I'm not sure how to refresh a pulldown. when I try to use the webclient to create an xml page based on the the select variable, I still get the old page.
to make it a bit easier, I used htmlunit scripter and got some code that should work but its java and I'm not sure how to port it to jython. Here it is:
try
{
page = webClient.getPage( url );
HtmlSelect selectField1 = (HtmlSelect) page.getElementById("pageNumSelection");
List<HtmlOption> options2 = selectField1.getOptions();
HtmlOption theOption3 = null;
for(HtmlOption option: options2)
{
if(option.getText().equals("100") )
{
theOption3 = option;
break;
}
}
selectField1.setSelectedAttribute(theOption3, true );
Have a look at HtmlForm getSelectedByName
HtmlSelect htmlSelect = form.getSelectByName("stuff[1].type");
HtmlOption htmlOption = htmlSelect.getOption(3);
htmlOption.setSelected(true);
Be sure that WebClient.setJavaScriptEnabled is called. The documentation seems to indicate that it is on by default, but I think this is wrong.
Alternatively, you can use WebDriver, which is a framework that supports both HtmlUnit and Selenium. I personally find the syntax easier to deal with than HtmlUnit.
If I understand correctly, the selection of an option in the select box triggers an AJAX calls which, once finished, modifies some part of the page.
The problem here is that since AJAX is, by definition, asynchronous, you can't really know when the call is finished and when you may inspect the page again to find the new content.
HtmlUnit has a class named NicelyResynchronizingAjaxController, which you can pass an instance of to the WebClient's setAjaxController method. As indicated in the javadoc, using this ajax controller will automatically make the asynchronous calls coming from a direct user interaction synchronous instead of asynchronous. Once the setSelectedAttribute method is called, you'll thus be able to see the changed made to the original page.
The other option is to use WebClient's waitForBackgrounfJavascript method after the selection is done, and inspect he page once the background JavaScript has ended, or the timeout has been reached.
This isn't really an answer to the question because I've not used HtmlUnit much before, but you might want to look at Selenium, and in particular Selenium RC. With Selenium RC you are able to control the interactions with a page displayed in a native browser (Firefox for example). It has developer API's for Java and Python amongst others.
I understand that HtmlUnit uses its own javascript and web browser rendering engine and I'm wondering whether that may be a problem.

Categories