简体   繁体   中英

How to select item from drop down list using Selenium WebDriver with Java?

I have a login page. In my test case I am able to login with the credentials but once I have logged in I am trying to select item from drop down list. I have the below code but I am getting an error

Select select = (Select) driver.findElement(By.id("Id goes here"));
        select.selectByValue("Value Goes here");

I am getting the below error Unable to locate element: {"method":"id","selector":"Value of Id"}

Note: the URL to login is different than the one on which select box is appearing. Can that be a problem? Is there a way to resolve it?

What you get is a NoSuchElementException when WebDriver cannot find the element based on your selection criteria.

Ensure that the WebElement can be located correctly using id or another selector. If the select element is inside an iframe , you will have to switch to it first using [ driver.switchTo().frame() ] ( http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebDriver.TargetLocator.html ).

Also, you cannot cast WebElement to Select .

Use:

WebElement elem = driver.findElement(By.id("listofnames"));
Select select = new Select(elem);
select.selectByValue("Name1");

This works for me:

String Xcode =  "//li[@class='dropdown']/a"; //<-your xpath here    
WebElement CourseSelector = driver.findElement(By.xpath(Xcode));
CourseSelector.click();
try {Thread.sleep(3000);} // o&c - GIVES TIME FOR ITEMS TO APPEAR
    catch (InterruptedException wtv)    
    {System.out.println("problem on wait with resource load" + wtv);    } 
Xcode =  "//ul/li/a[text()='" + Your_Menu_Item_Here + "']"; // <- again your xpath here
CourseSelector = driver.findElement(By.xpath(Xcode));
CourseSelector.click();

Select dropdown1;

    dropdown2 = new Select (mozila.findElement(By.id("of the dropdown1"))); 

            dropdown2.selectByValue("9");

Select dropdown2;

    dropdown2 = new Select (mozila.findElement(By.id("of the dropdown2")));  

    dropdown3.selectByValue("2018");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM