Edward Wang
Edward Wang

Reputation: 13

Dropdown menu element not found with Selenium Java

Whenever I look for the first dropdown menu (the state/province one) at this website with the Selenium ChromeDriver, it always returns an element not found error.

I've already tried explicit waits, finding the element by CSS, XPath, name, etc, and also ChromeDriver options. I've even tried to run JavaScript and find the element through its XPath and changing selecting it, but it doesn't work unless I inspect the page first.

Is this a ChromeDriver or website problem? I'm probably going to resort to a Java Robot and doing it more manually.

My initialization code:

WebElement selectElement = driver.findElement(By.xpath("/html/body/div[1]/div[1]/div/div/div[2]/font/table[1]/tbody/tr[1]/td[2]/select"));
Select select = new Select(selectElement);

Upvotes: 0

Views: 1598

Answers (3)

Ghanshyam
Ghanshyam

Reputation: 182

The Element on which you want perform operation, that is available into an IFrame so:

1) Switch to Iframe first:

driver.switchTo().frame(driver.findElement(By.id("iFrameResizer0")));

2) Then perform the operation to select the value from drop down box:

 WebElement element = driver.findElement(By.xpath("//select[@name='filter_data8']"));
 Select select = new Select(element);
 select.selectByVisibleText("Alaska");

Upvotes: 0

NarendraR
NarendraR

Reputation: 7708

While inspecting element i found that there is an iframe on the website and the content wrapped on it. Check it here:

enter image description here

So while you try to deal with element present in iframe it returns NoSuchElementException. First you need to switch into iframe and then only it will work.

Better approach is use Explicit Wait condition to switch into it as it wait until frame get loaded on the page then switch the focus. Refer this code:

(new WebDriverWait(driver,20)).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("iFrameResizer0")));

And then select the dropdown value:

WebElement state = new driver.findElement(By.name("filter_data8"));
new Select(state).selectByVisibleText("state_value");

I would suggest you to go with recommended locator selection. Refer this blog

Upvotes: 0

Sameer Arora
Sameer Arora

Reputation: 4507

An iframe is present on the page, so you need to first switch on the iframe and then click on the element.
Also, in the answer i have used relative xpath to find the element instead of the absolute xpath as relative xpath is much more stable.

Your code should be like:

 // Switch the driver to iframe
 driver.switchTo().frame(driver.findElement(By.id("iFrameResizer0")));

 // Find the element by relative xpath
 WebElement element = driver.findElement(By.xpath("//select[@name='filter_data8']"));
 Select select = new Select(element);
 select.selectByIndex(2);

Upvotes: 0

Related Questions