首页 > 解决方案 > 无法在 Select with Selenium 中选择选项

问题描述

当我尝试<select>在 Selenium 中选择一个选项时遇到问题。

Select select = new Select(element);
actions.moveToElement(element);
select.selectByValue("100000");

这简直给了我ElementClickIntercepted. 试图点击它也给了我ElementClickIntercepted。尝试用 JS 点击它会给我一个NullPointerException. 我可以使用元素选择器在 Firefox 中轻松选择它,因此选择顶部没有任何东西阻止我单击它。

什么是拦截点击?通常是因为一个元素覆盖了另一个元素,它会在测试结果中告诉我,但这里没有。

<div class="pull-left">
<select name="nb" class="form-control">
<option value="10">10</option><option value="20">20</option><option value="50">50</option><option value="100000">All</option>
</select>
</div>

选择 xPath:

//select[@name="nb"]

它是页面上唯一的选择。

标签: javaseleniumselenium-webdriver

解决方案


由于元素是<select>理想的元素,因此您需要使用Select类。要调用click()值为1000的选项,您需要诱导WebDriverWait并且elementToBeClickable()您可以使用以下任一 Locator Strategies

  • cssSelector

    new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("select.form-control[name='nb']")))).selectByValue("100000");
    
  • xpath

    new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//select[@class='form-control' and @name='nb']")))).selectByValue("100000");
    

推荐阅读