在 Amazon 中自动执行下拉列表

Automating a dropdown in amazon

提问人:Yash Thakur 提问时间:10/8/2023 最后编辑:YaroslavmYash Thakur 更新时间:10/8/2023 访问量:34

问:

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

enter image description here

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 浏览器自动化

评论


答:

0赞 JeffC 10/8/2023 #1

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

Exception in thread "main" org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "div"

这样做的原因是需要一个 SELECT 元素,但您的定位器返回一个 DIV。您可以通过使用 ID 将定位器更改为指向 SELECT 元素来轻松解决此问题。Select()

By.id("searchDropdownBox")

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

  1. 找到下拉列表并单击它 - 由于下面的步骤 4 而没有必要
  2. 滚动到下拉列表 - 您已经单击了它,因此此步骤是不必要的
  3. 等到下拉列表可点击 - 同样,您已经点击了它,所以这一步是不必要的
  4. 将下拉列表转换为元素,然后选择下拉列表中的第一项Select

您的整个代码可以简化为

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

按 ID(简单且有弹性的定位器)查找 SELECT 元素,将其转换为 以便于使用,然后使用索引选择所需的 OPTION。Select