在亚马逊自动化下拉菜单

问题描述 投票:0回答:1

实际上,我正在尝试自动化亚马逊网站,我必须从下拉列表中选择一个类别,如快照所示。但当我尝试这样做时,它说

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);
java selenium-webdriver automation browser-automation
1个回答
0
投票

您尚未根据您提供的代码发布正确的错误。正确的错误是

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")

你还有很多不必要的代码。你的代码基本上是这样的

  1. 找到下拉菜单并单击它 - 由于下面的步骤 4,因此不需要
  2. 滚动到下拉菜单 - 您已经单击了它,因此无需执行此步骤
  3. 等到下拉菜单可单击 - 再次,您已经单击了它,因此无需执行此步骤
  4. 将下拉列表转换为
    Select
    元素并选择下拉列表中的第一项

您的整个代码可以简化为

Select dropdown = new Select(driver.findElement(By.id("searchDropdownBox")));
dropdown.selectByIndex(1);

通过 ID(简单且有弹性的定位器)查找 SELECT 元素,将其转换为

Select
,以便更容易使用,然后使用索引选择所需的选项。

© www.soinside.com 2019 - 2024. All rights reserved.