'Selecting element from drop down list using selenium web driver

I want to select element from drop down list but in html they have used <img> tag. How can I achieve my goal?

This is stuff from my code:

public void country() {
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    Select country1 = new Select(country);
    country1.selectByVisibleText("Canada");
}

I am getting this error while running testNg test

org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "img"



Solution 1:[1]

As you mentioned:

... but in html they have used <img> tag.

Which your error confirms. So, as per the error, you obviously cannot use Select().

You did not provide enough information to give a complete answer! But think about what the user would do. First they would click on the outer element:

driver.findElement(By.id(country)).click();  // replace country with appropriate ID, or other locator!

After this the user will have to wait for the menu to completely appear. Same for your code!

Next, the user can click on the desired option:

driver.findElement(By.id("Canada")).click();   // again, replace "Canada" with appropriate locator!

It is quite possible that the resulting menu will be long. Instead of the above .click() you may need to grab all the menu items based on some locator, and then iterate over all of them:

List<WebElement> items = driver.findElements(By....);
for(WebElement item : items) {
    if(item.getText().equals("Canada"))
        item.click();
}

Solution 2:[2]

Use the following code:

List<WebElement> lstOptions=Country1.getoptions();
for(WebElement lstOption:lstOptions){
if(lstOption.gettext().tolowercase().equals("canada"))
lstOption.click();
}

Solution 3:[3]

How to find dropdown list value..... Use this code sure its help you!!!

 driver.findElement(By.xpath("ur xpath")).click();

 new Select(driver.findElement(By.name("EventType"))).selectByVisibleText("Birthday");

or

 new Select(driver.findElement(By.id("city"))).selectByValue("Op3");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SiKing
Solution 2 Nainappa Illi
Solution 3 Paul Draper