实际上,我正在尝试自动化亚马逊网站,我必须从下拉列表中选择一个类别,如快照所示。但当我尝试这样做时,它说
ElementNotInteractableException
。
WebElement dropDown = driver.findElement(By.xpath("//div[@class='nav-search-scope nav-sprite']"));
dropDown.click();
// Scroll the dropdown element into view using JavaScript
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("arguments[0].scrollIntoView(true);", dropDown);
// Wait for the dropdown to be clickable and visible
wait.until(ExpectedConditions.elementToBeClickable(dropDown));
//selecting dropdown
Select select = new Select(dropDown);
select.selectByIndex(1);
您尚未根据您提供的代码发布正确的错误。正确的错误是
Exception in thread "main" org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "div"
其原因是
Select()
需要一个 SELECT 元素,但你的定位器返回一个 DIV。您可以通过使用 ID 将定位器更改为指向 SELECT 元素来轻松解决此问题,
By.id("searchDropdownBox")
你还有很多不必要的代码。你的代码基本上是这样的
Select
元素并选择下拉列表中的第一项您的整个代码可以简化为
Select dropdown = new Select(driver.findElement(By.id("searchDropdownBox")));
dropdown.selectByIndex(1);
通过 ID(简单且有弹性的定位器)查找 SELECT 元素,将其转换为
Select
,以便更容易使用,然后使用索引选择所需的选项。