How to select a value from Drop-Down in DHTML Grid Using Selenium WebDriver?
enter image description here
By Double click in UMO Column, a drop-down will be seen.
I need to pick a item from that drop-down. But locator is unable to find the Drop-Down.
I am able to double click the field, not able to proceed after that(i.e., Control is not able to locate the drop-down).
Through Firebug, it is shown "Select Class"..
Is there any work around in selenium webdriver to select the item from that drop-down...?
Will be very helpful if u share idea regarding this.
new SelectElement(driver.FindElement(By.ClassName("<className>"))).SelectByIndex("");
new SelectElement(driver.FindElement(By.ClassName("<className>"))).SelectByText("");
new SelectElement(driver.FindElement(By.ClassName("<className>"))).SelectByValue("");
Here is the example code that may help. Create a instance of Select Class from WebElement.
public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
driver.get("http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select");
driver.switchTo().frame(driver.findElement(By.id("iframeResult")));
WebElement elem = driver.findElement(By.tagName("select"));
Select se=new Select(elem);
se.selectByIndex(3);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver .close();
}
WebElement element = driver.findElements(By.xpath("//*[#id=\"institutionName\"]/option"));
Select select = new Select(element);
select.selectByVisibleText("value");
//select.selectByIndex(0);
//select.selectByValue("1");
Related
I have used the following code.I am getting NoSuchElementException error when I am trying to run this code for make my trip site
public class suggestiveDropdown_MMTsite {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Webdriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.makemytrip.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Actions a = new Actions(driver);
WebElement source = driver.findElement(By.id("fromCity"));
a.moveToElement(source).click().build().perform();
a.moveToElement(source).sendKeys("MUM").build().perform();
/*WebDriverWait w = new WebDriverWait(driver,5);
w.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("react-autowhatever-1")));*/
WebElement dropdown1 = driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
a.moveToElement(dropdown1).click().build().perform();
WebElement destination = driver.findElement(By.id("toCity"));
a.moveToElement(destination).click().build().perform();
a.moveToElement(destination).sendKeys("DEL").build().perform();
a.moveToElement(dropdown1).click().build().perform();
}
}
You need to re-identify dropdown1 as the second time it appears it's in a different location in the source an a different webelement.
I see your logic and why you think it would work as it has the same ID - but when you use your By you're returning a specific webelement from the DOM. Even though the ID is reused due to whatever javascript magic, the webelement is different (it's in a different position after all).
The two bits I'm talking about....
1/ This part of your code finds the object:
WebElement dropdown1 = driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
a.moveToElement(dropdown1).click().build().perform();
2/ It is no longer dropdown 1. It has the SAME ID, but it's a different webelement
a.moveToElement(dropdown1).click().build().perform();
Solution here is re-get the element and I suggest to rename it to help clarify the difference. Change your last line to something like this:
WebElement firstItemInToCity= driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
a.moveToElement(firstItemInToCity).click().build().perform();
I've had another look. This works for me:
driver.get("https://www.makemytrip.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Actions a = new Actions(driver);
//from city:
WebElement source = driver.findElement(By.id("fromCity"));
source.click();
source.sendKeys("MUM");
//select first item in the list
WebElement dropdown1 = driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
dropdown1.click();
//Get the to city
WebElement destination = driver.findElement(By.id("toCity"));
destination.click();
destination.sendKeys("DEL");
//pick the first item in the list
WebElement firstItemInToCity= driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
firstItemInToCity.click();
You do not need to use the actions to interact. Using the selenium native interactions seems fine.
I did have increase the implicit timeout as the page is quote slow to load for me.
I was using below code to select an item from a list box using selenium, since select was not available .. How can I achieve the same in Karate.
public void selectOption(WebDriver driver, List ele, String option) throws InterruptedException {
for(WebElement i: ele){
if (i.getText().equalsIgnoreCase(option)){
Actions actions = new Actions(driver);
actions.moveToElement(i);
actions.click().perform();
break;
}
}
Here is the documentation: https://github.com/intuit/karate/tree/master/karate-core#select
Something like this:
* select('select[name=data1]', '{}Option Visible Text')
If you are still stuck, please follow this process so that we can fix anything if needed: https://github.com/intuit/karate/tree/master/examples/ui-test
In the following example, I have to click only for Jet Airways. It appears that the xpath selected is correct since it gives the right only from the selection.
http://i.imgur.com/8TiOgha.png
However when this same is being pulled by Selenium WebDriver, it says element not visible. But it still gives a Button with zero length text string. as given in watch window.
http://i.imgur.com/jrR0221.png
I would appreciate if anyone can help me to point if any error I am making since I am new to VBA
Not sure if your XPath is correct and is locating the right static element...
You may use this for locating 'Jet Airways'
//label[text()[contains(.,'Jet Airways')]]
Also, using .click(), try clicking on the 'Airlines' dropdown before locating the 'Airlines Dropdown' XPath
//span[#title='Airlines']
Update:
public class SkyScanner
{
static String chkBxXpth = "//label[#class='dropdown-item cfx']/input[#checked]";
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
Actions actions = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("http://skyscanner.cntraveller.com/en-GB/flights#/result?originplace=AUH&destinationplace=LHR");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[#title='Airlines']")));
driver.findElement(By.xpath("//span[#title='Airlines']")).click();
List<WebElement> chkBx = driver.findElements(By.xpath(chkBxXpth));
for(WebElement i : chkBx)
{
actions.moveToElement(i).click().perform();
}
driver.findElement(By.xpath("//label[text()[contains(.,'Jet Airways')]]")).click();
}
}
My Code:
public class asdadsd {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://talentrack.in");
driver.findElement(By.xpath(".//*[#id='header']/div[2]/div[2]/div[2]/a/span")).click();
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='userlogin']/div/div[4]/a[1]")));
driver.findElement(By.xpath(".//*[#id='userlogin']/div/div[4]/a[1]")).click();
WebElement name = driver.findElement(By.xpath(".//*[#id='name']"));
name.sendKeys("anyname");
//WebDriverWait wait = new WebDriverWait(driver, 20);
//wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("select[id='cat_id'][name='cat_id']")));
Thread.sleep(5000L);
//WebElement category = driver.findElement(By.cssSelector("select[id='cat_id'][name='cat_id']"));
WebElement category = driver.findElement(By.cssSelector("#cat_id"));
Select a =new Select(category);
a.selectByValue("5");
}
}
What is wrong with category drop-down ? I'm able to fill values in other drop-downs. Please Help me in getting rid of this.
Error:
Element is not currently visible and so may not be interacted with
Command duration or timeout: 13 milliseconds
I applied wait to, still it is not working.
#Kishan,
In your code WebDriver unable to select the dropdown because it found two matching element with your css selector. PFA the screenshot. So if you want to use css selector then you can use:
#cat_id[class='input-control modal-tab-selection placeholder-color'] instead of #cat_id.
WebElement category = driver.findElement(By.cssSelector("#cat_id[class='input-control modal-tab-selection placeholder-color']"));
Select a =new Select(category);
a.selectByValue("5");
I hope this will help.
WebElement category = driver.findElement(By.xpath(".//*[#id='cat_id'][#data-message='required']"));
Select a =new Select(category);
a.selectByValue("4");
Finally i got it..
This was the xpath which helped me to uniquely identify the dropdown. Thanks Vaibhav for your help. Never trust xpath, better create your own. ha ha..
Happy Learning. :-)
Am doing automation tesing using selenium, i need help in regarding how to select radio button.If possible help me with selenium java code.
Assuming you have selenium set up its just:
selenium.click('radio button locator');
You may want to look at the selenium javadoc http://release.seleniumhq.org/selenium-remote-control/0.9.2/doc/java/com/thoughtworks/selenium/Selenium.html
click > xpath=(//input[#type='checkbox'])[position()=1]
click > xpath=(//input[#type='checkbox'])[position()=2]
click > xpath=(//input[#type='checkbox'])[position()=3]
click > xpath=(//input[#type='checkbox'])[position()=4]
etc ...
use this commands to select random and any radio button
public class radioExamJavaScr {
public static void main(String[] args) throws IOException {
WebDriver driver = new FirefoxDriver();
EventFiringWebDriver dr = new EventFiringWebDriver(driver);
dr.get("http://www.makemytrip.com/");
dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
((JavascriptExecutor)dr).executeScript("document.getElementById('roundtrip_r').click();");
WebElement one_way = (WebElement)((JavascriptExecutor)dr).executeScript("return document.getElementById('oneway_r') ;");
System.out.println(one_way.isSelected());
WebElement round_trip = (WebElement)((JavascriptExecutor)dr).executeScript("return document.getElementById('roundtrip_r') ;");
System.out.println(round_trip.isSelected());
}
}
In the above example I am selecting radio button with "ROUND TRIP" using "JavaScript".
The last four lines are to verify and see whether the expected radio button is selected in the page or not.
NOTE: I am giving simple easy solution to solve a problem (selecting a radio) in the choosen webpage. A better code can be written. (user can write a method to accept radio ID and loop through all the existing radio button to see which one of them is selected).
I use this method:
String radioButtonId = "radioButtonId";
selenium.focus("id=" + radioButtonId);
selenium.click("id=" + radioButtonId, "concreteRadioButtonValue");
What you can do is this:
Create a method with a WebElement return type, and use the Method findElement(). Example:
WebDriver test;
test = new FirefoxDriver();
public static WebElement checkAndGet(By b) throws Exception {
return test.findElement(b);
}
Store the WebElement and use the Method click(). Example:
WebElement radiobutton = checkAndGet(By.xpath("//span[#class='label ng-binding']");
radiobutton.click();
Hope this helps!
Test Scenario : Select Gender(Female) radio button
Steps:
Launch new Browser
Open URL http://toolsqa.wpengine.com/automation-practice-form/
Select the Radio button (female) by Value ‘Female’
Code :
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver(); // Step 1 - Launch Browser
driver.get("http://toolsqa.com/automation-practice-form"); // Step 2 - Open Test URL
List<WebElement> rdBtn_Sex = driver.findElements(By.name("sex")); //
int size = rdBtn_Sex.size();
System.out.println("Total no of radio button :"+size);
for (int i=0; i< size; i++)
{
String sValue = rdBtn_Sex.get(i).getAttribute("value"); // Step 3 - 3. Select the Radio button (female) by Value ‘Female’
System.out.println("Radio button Name "+sValue);
if (sValue.equalsIgnoreCase("Female"))
{
rdBtn_Sex.get(i).click();
}
}
What you should do all the time is provide a locator for every object within a page and then use a method.
Like
driver.findElement(By.xpath(//CLASS[contains(., 'what you are looking for')])).click();