【问题标题】:Dropdown menu element not found with Selenium JavaSelenium Java 未找到下拉菜单元素
【发布时间】:2020-10-01 21:22:11
【问题描述】:
每当我使用 Selenium ChromeDriver 在 website 查找第一个下拉菜单(州/省菜单)时,它总是返回一个元素未找到错误。
我已经尝试过显式等待,通过 CSS、XPath、名称等以及 ChromeDriver 选项来查找元素。我什至尝试运行 JavaScript 并通过其 XPath 查找元素并更改选择它,但除非我先检查页面,否则它不起作用。
这是 ChromeDriver 还是网站问题?我可能会求助于 Java 机器人并更多地手动完成。
我的初始化代码:
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);
【问题讨论】:
标签:
java
selenium
google-chrome
selenium-webdriver
automated-tests
【解决方案1】:
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");
【解决方案2】:
在检查元素时,我发现网站上有一个 iframe,并且上面包含了内容。在这里检查:
因此,当您尝试处理 iframe 中存在的元素时,它会返回 NoSuchElementException。首先你需要切换到 iframe,然后只有它才能工作。
更好的方法是使用显式等待条件切换到它,因为它等待框架加载到页面上然后切换焦点。参考这段代码:
(new WebDriverWait(driver,20)).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("iFrameResizer0")));
然后选择下拉值:
WebElement state = new driver.findElement(By.name("filter_data8"));
new Select(state).selectByVisibleText("state_value");
我建议您使用推荐的定位器选择。参考这个blog
【解决方案3】:
页面上存在 iframe,因此您需要先打开 iframe,然后单击该元素。
此外,在答案中,我使用相对 xpath 来查找元素而不是绝对 xpath,因为相对 xpath 更加稳定。
你的代码应该是这样的:
// 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);