After moving to the value which is present in dropdown, i want to get it using actions class. Below is the code i have written. i am trying to print the dropdown values. HTML tag for dropdown is input(for select i have code). Please help me
public static void caseSearch()
{
try
{
Actions a=new Actions(driver);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
logger.info("clicking on cases tab :: ");
driver.findElement(By.xpath(loader.getProperty(Constants.CaseTab))).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement ele=driver.findElement(By.xpath(loader.getProperty(Constants.CaseSearch)));
ele.click();
for(int i=0;i<=20;i++)
{
//i want to print the first value of dropdown in console
a.sendKeys(Keys.DOWN,Keys.DOWN,Keys.DOWN).build().perform();
String value=ele.getText();
System.out.println("value is = "+value);
a.sendKeys(Keys.DOWN,Keys.DOWN).build().perform();
Thread.sleep(3000);
a.sendKeys(Keys.ENTER).build().perform();
}
}
catch(Exception e)
{
logger.info("case search method is not executed :: " +e);
}
}
I think you forgot to get the value from the dropdown box.
You need to use the Select Class to get it.
Actions key = new Actions(browser);
WebElement dropdownElement = this.browser.findElement(By.xpath("YOUR DROPDOWN ELEMENT"));
Select dropOptions = new Select(dropdownElement);
int elements = dropOptions.getOptions().size();
for (int i = 0; i < elements; i++) {
dropdownElement.click();
if (i > 0) {
Thread.sleep(1000L);
key.sendKeys(Keys.DOWN).build().perform();
Thread.sleep(1000L);
key.sendKeys(Keys.ENTER).build().perform();
}
else {
Thread.sleep(1000L);
ActionPerformers.sendActionKey(browser, Keys.ENTER);
}
System.out.println("ELEMENT " + i + " -> " + dropOptions.getFirstSelectedOption().getText()); //Here you will get the selected Value...
}
This is only an exemple, I hope it suits you.
Related
I have done this
List<WebElement> element= driver.findElements(By.xpath(""));
for(int i=0;element.size();i++)
{
driver.findElements(By.xpath("")).isDisplayed();
driver.findElements(By.xpath("")).click();
}
I am new to java and selenium , so I thought of doing this. Is this logic correct or am I wrong? If wrong(most probably) , can you please rectify and explain alongside , wud be very helpful.
I get element not interactable error on this.
In case you are looking for method to wait for one of two elements to appear and then to click on the appeared element you can use this method:
public String waitForOneOfTwoElements(String xpath1, String xpath2){
wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath1)),
ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath2))));
if(waitForElementToBeVisible(xpath1)){
return xpath1;
}else if(waitForElementToBeVisible(xpath2)){
return xpath2;
}
}catch (Throwable t){
return null;
}
}
Where waitForElementToBeVisible is:
public boolean waitForElementToBeVisible(String xpath) {
wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
return true;
}catch (Throwable t) {
return false;
}
}
Now, when you get the appeared element you can simply click it with:
String appearedElementXpath = waitForOneOfTwoElements(xpath1,xpath2);
driver.findElement(By.xpath(appearedElementXpath)).click();
On https://www.zillow.com I am trying to verify search using auto suggestion box.
I have written below code:
public static void verifySearch() {
try {
WebElement searchbar = driver.findElement(By.id("search-box-input"));
searchbar.sendKeys("sea");
// Thread.sleep(10);
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[#role='listbox']/li")));
List<WebElement> list = driver.findElements(By.xpath("//ul[#role='listbox']//li"));
System.out.println("Total no of suggestions in search box:::====> " + list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getText());
if (list.get(i).getText().contains("Seattle WA")) {
/*
* JavascriptExecutor js = (JavascriptExecutor)driver;
* js.executeScript("arguments[0].click();", list.get(i));
*/
list.get(i).click();
break;
}
}
System.out.println("out");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
e.printStackTrace();
}
Here for auto suggestion list I am using following xpath but it doesn't work at run time:"//ul[#role='listbox']//li"
Can anybody guide where I am wrong.
Note:on this website autosuggestion is starts to be displayed after 3chars in search field.
Here my friend. Please try to execute the below code. You can now try to fix your issue with this simple solution.
try {
WebElement searchbar = driver.findElement(By.id("search-box-input"));
searchbar.click();
for( char character : "sea".toCharArray() )
{
searchbar.sendKeys(String.valueOf(character));
Thread.sleep(2000);
}
List<WebElement> list = driver.findElements(By.xpath("//ul[#role='listbox']//li"));
System.out.println("Total no of suggestions in search box:::====> " + list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getText());
if (list.get(i).getText().contains("Seattle WA")) {
/*
* JavascriptExecutor js = (JavascriptExecutor)driver;
* js.executeScript("arguments[0].click();", list.get(i));
*/
list.get(i).click();
break;
}
}
System.out.println("out");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
e.printStackTrace();
}
I have a Google Search bar with a drop down and the options are under a UL and the actual ones under the li. I am unable to retrieve the data field of the li, while I am able to retrieve the count. Have tried with the List elements and looping thru it ,but no luck. The drop with all the Options is Not visible.
I have to print the Titles associated with the li using Selenium Web driver.
Below is what I tried:
ul class=classname> xxx – GSA 2 days ago
wb.findElement(By.xpath("<>")).click();
List items = html_list.findElements(By.tagName("li")); System.out.println("The size of the elements is " + items.size()); for(WebElement item : items) { html_list.sendKeys( Keys.DOWN ); //simulate visual movement
wb.manage().timeouts().implicitlyWait(1000, TimeUnit.SECONDS); System.out.println(item.getText());
}
Hypohesis #1: You don't wait for the page to load after the click on line 1. The li elements are in the DOM but they are not completely loaded. You could test the hypothesis by introducing a delay between line 1 and line 2. I have code that I use to wait for page loads but the specifics depend on the JavaScript framework (e.g. jQuery, AngularJs), on the loading spinner implementation and browser readystate. My readystate logic looks like this:
/**
* Wait for browser readystate to be complete. But don't wait forever.
*
* #param webDriver
*/
public void waitForBrowserReadystateComplete(WebDriver webDriver) {
for (int a=0; a<20; a++) {
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
if (javascriptExecutor.executeScript("return document.readyState")
.toString().equals("complete")) {
break;
}
sleepResponsibly(500);
}
}
public void sleepResponsibly(int timeMillisecond){
try{
Thread.sleep(timeMillisecond);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
Hypthosis #2: The text nodes are complex. I have experienced a failure in method getText() to return text when the text nodes code complex formatting. I got around this by invoking the following instead:
public static String getTextFromElementsTextNodes(WebDriver webDriver, WebElement element) throws IllegalArgumentException {
String text = "";
if (webDriver instanceof JavascriptExecutor) {
text = (String)((JavascriptExecutor) webDriver).executeScript(
"var nodes = arguments[0].childNodes;" +
"var text = '';" +
"for (var i = 0; i < nodes.length; i++) {" +
" if (nodes[i].nodeType == Node.TEXT_NODE) {" +
" text += nodes[i].textContent;" +
" }" +
"}" +
"return text;"
, element);
} else {
throw new IllegalArgumentException("driver is not an instance of JavascriptExecutor");
}
return text;
}
A caveat is that getTextFromElementsTextNodes() may return non-ASCII charcters so I do the following:
System.out.println(getTextFromElementsTextNodes(wb,item).replaceAll("[^\\x00-\\x7F]", " "));
I could finally able to retrieve the options under the li. This is what I did and it worked
for(WebElement MyListOptions: listOfLiTags) {
String myoptions=serchOptions.getAttribute("<<The actual attribute value which is storing my options>>");
System.out.println("THE List Options are" + txt3);
}
I am trying to click on the object, to show the list of value pop-up.
I used the following script, but unable to populate the list value pop-up.
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
Thread.sleep(1000L);
Is there any other way to click and wait for the object?
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
WebDriverWait wait = new WebDriverWait(Driver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id("yourId")));
There are other conditions like visibilityOf so choose the one which suits you most - documentation here.
String mainWindowHandle = driver.getWindowHandle();
System.out.println(mainWindowHandle);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(OR.getProperty(Object)));
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
PageUtil.sleep(3000);
Set<String> s1 = driver.getWindowHandles();
Iterator<String> ite = s1.iterator();
while (ite.hasNext()) {
String popupHandle = ite.next().toString();
System.out.println(popupHandle + " Present Pop Up window name");
if (!popupHandle.contains(mainWindowHandle)) {
driver.switchTo().window(popupHandle);
}
}
WebDriverWait wait = new WebDriverWait(Driver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id("yourId")));
Driver.findElement(By.id("yourId")).click();
driver.switchTo().window(mainWindowHandle);
After clicking you can wait using FluentWait,
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
refer this for more info
I'm not quite familiar with java syntax, but I'll give you php code and you can write similar. The idea is to find HTML element by tag and get it's id BEFORE YOU CLICK. Then AFTER THE CLICK wait for the id to change.
It looks like this:
class MySeleniumCondition extends WebDriverExpectedCondition{
public static function htmlElementIdIsNot($htmlElementId) {
return new WebDriverExpectedCondition(
function ($driver) use ($htmlElementId) {
$htmlElement = $driver->findElement(WebDriverBy::tagName('html'));
return $htmlElementId != $htmlElement->getId();
}
);
}
}
// .............. somehere in a class:
public function waitForNewPage($oldHtmlElementId, $time = 10){
try{
$this->driver->wait($time)->until(
MySeleniumCondition::htmlElementIdIsNot(
$oldHtmlElementId
)
);
return true;
}catch(TimeOutException $e){
return false;
}
}
// use this only when you are sure the page will reload
public function clickAndWait(WebDriverBy $locator, $time = 10){
$webElement = $this->driver->findElement($locator);
$oldHtmlElement = $driver->findElement(WebDriverBy::tagName('html'));
$oldHtmlElementId = $oldHtmlElement->getId();
$webElement->click();
$this->waitForNewPage($oldHtmlElementId, $time);
return true;
}
I am unable to switch to Modal Dialog of given example
http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm
I don't know how to get element on modal Dialog
Use
following methods to switch to modelframe
driver.switchTo().frame("ModelFrameTitle");
or
driver.switchTo().activeElement()
Hope this will work
What you are using is not a model dialog, it is a separate window.
Use this code:
private static Object firstHandle;
private static Object lastHandle;
public static void switchToWindowsPopup() {
Set<String> handles = DriverManager.getCurrent().getWindowHandles();
Iterator<String> itr = handles.iterator();
firstHandle = itr.next();
lastHandle = firstHandle;
while (itr.hasNext()) {
lastHandle = itr.next();
}
DriverManager.getCurrent().switchTo().window(lastHandle.toString());
}
public static void switchToMainWindow() {
DriverManager.getCurrent().switchTo().window(firstHandle.toString());
Try the below code. It is working in IE but not in FF22. If Modal dialog found is printed in Console, then Modal dialog is identified and switched.
public class ModalDialog {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new InternetExplorerDriver();
//WebDriver driver = new FirefoxDriver();
driver.get("http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm");
String parent = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement push_to_create = wait.until(ExpectedConditions
.elementToBeClickable(By
.cssSelector("input[value='Push To Create']")));
push_to_create.click();
waitForWindow(driver);
switchToModalDialog(driver, parent);
}
public static void waitForWindow(WebDriver driver)
throws InterruptedException {
//wait until number of window handles become 2 or until 6 seconds are completed.
int timecount = 1;
do {
driver.getWindowHandles();
Thread.sleep(200);
timecount++;
if (timecount > 30) {
break;
}
} while (driver.getWindowHandles().size() != 2);
}
public static void switchToModalDialog(WebDriver driver, String parent) {
//Switch to Modal dialog
if (driver.getWindowHandles().size() == 2) {
for (String window : driver.getWindowHandles()) {
if (!window.equals(parent)) {
driver.switchTo().window(window);
System.out.println("Modal dialog found");
break;
}
}
}
}
}
Solution in R (RSelenium):
I had a popup dialog (which is dynamically generated) and hence undetectable in the original page source code
Here are methods which worked for me:
Method 1: Simulating Pressing keys for Tabs and switching to that modal dialog
My current key is focussed on a dropdown button behind the modal dialog box
remDr$sendKeysToActiveElement(list(key = "tab"))
Sys.sleep(5)
remDr$sendKeysToActiveElement(list(key = "enter"))
Sys.sleep(15)
Method 2: Bring focus to the frame(or iframe) if you can locate it
date_filter_frame <- remDr$findElement(using = "tag name", 'iframe')
date_filter_frame$highlightElement()
Sys.sleep(5)
remDr$switchToFrame(date_filter_frame)
Sys.sleep(2)
Now you can search for elements in the frame. Remember to put adequate Sys.sleep in between commands for elements to load properly (just in case)
date_filter_element <- remDr$findElement(using = "xpath", paste0("//*[contains(text(), 'Week to Date')]"))
date_filter_element$highlightElement()
Try this code, include your object names & variable to work.
Set<String> windowids = driver.getWindowHandles();
Iterator<String> iter= windowids.iterator();
for (int i = 1; i < sh.getRows(); i++)
{
while(iter.hasNext())
{
System.out.println("Main Window ID :"+iter.next());
}
driver.findElement(By.id("lgnLogin_UserName")).clear();
driver.findElement(By.id("lgnLogin_UserName")).sendKeys(sh.getCell(0,
i).getContents());
driver.findElement(By.id("lgnLogin_Password")).clear();
driver.findElement(By.id("lgnLogin_Password")).sendKeys(sh.getCell(1,
i).getContents());
driver.findElement(By.id("lgnLogin_LoginButton")).click();
Thread.sleep(5000L);
windowids = driver.getWindowHandles();
iter= windowids.iterator();
String main_windowID=iter.next();
String tabbed_windowID=iter.next();
System.out.println("Main Window ID :"+main_windowID);
//switch over to pop-up window
Thread.sleep(1000);
driver.switchTo().window(tabbed_windowID);
System.out.println("Pop-up window Title : "+driver.getTitle());
I have tried it, it works for you.
String mainWinHander = webDriver.getWindowHandle();
// code for clicking button to open new window is ommited
//Now the window opened. So here reture the handle with size = 2
Set<String> handles = webDriver.getWindowHandles();
for(String handle : handles)
{
if(!mainWinHander.equals(handle))
{
// Here will block for ever. No exception and timeout!
WebDriver popup = webDriver.switchTo().window(handle);
// do something with popup
popup.close();
}
}
Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.
WebElement link = // element that will showModalDialog()
// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
"var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
link);
// wait for there to be two windows and choose the one that is
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
.until(new Function<WebDriver, Boolean>() {
#Override
public Boolean apply(final WebDriver driver) {
final String[] windowHandles =
driver.getWindowHandles().toArray(new String[0]);
if (windowHandles.length != 2) {
return false;
}
if (windowHandles[0].equals(parentWindowHandle)) {
driver.switchTo().window(windowHandles[1]);
} else {
driver.switchTo().window(windowHandles[0]);
}
return true;
}
});
Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model,
This will works once model appeared then control take a place into model and click the expected element.
have to import javascriptexector
like below,
Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);
P.S. 1 adding my 2 cents even though the question is too old
public void PressEnterKey()
{
var simulator = new InputSimulator();
simulator.Keyboard.KeyPress(VirtualKeyCode.RETURN);
}
you can create a method like the above and call it where it is required.
P.S. 2 - you can change the keyboard inputs as well (like up arrow, down arrow, page down etc)