Selenium:submit()工作正常,但click()没有

Dmi*_*try 1 java junit selenium selenium-webdriver

我有提交按钮,它只是页面上的一个,而且它的形式.

HTML部分:

<form class="search-form ng-touched ng-dirty ng-valid" novalidate="" style="" xpath="1">

<div class="row">...</div>
<div class="row">...</div>
<div class="row">...</div>
<div class="form__actions" xpath="1">
    <div class="form__buttons">
      <!---->
      <div class="btn__wrapper">
        <button class="btn btn__primary" type="submit">
          Select My Car
        </button>
      </div>
    </div>
  </div>

</form>
Run Code Online (Sandbox Code Playgroud)

所以,我正在采取xpath:

//button[@type='submit']
Run Code Online (Sandbox Code Playgroud)

我通过submit()成功地按下它(让我跳过WebDriver init,它很好):

  WebElement searchButton = driver.findElement(By.xpath("//button[@type='submit']"));
  searchButton.submit();
Run Code Online (Sandbox Code Playgroud)

(和一些搜索执行)

但是当我试图通过点击()按下它时

WebElement searchButton = driver.findElement(By.xpath("//button[@type='submit']"));
        searchButton.click();
Run Code Online (Sandbox Code Playgroud)

它没有在启动的浏览器中按下,同时Junit测试为绿色(不是测试,只是按下按钮):

@Test
    public void test() {
        WebElement button = driver.findElement(By.xpath("//button[@type='submit']"));
        button.click();
    }
Run Code Online (Sandbox Code Playgroud)

可以请有人解释,为什么在这种情况下submit()成功按下按钮,但是单击() - 否.而且我不明白,为什么"test"是绿色的,当我们尝试点击()时,如果查看驱动程序启动的浏览器则没有执行.

更新: 我试过了

WebElement button = driver.findElement(By.xpath("//button[@type='submit']"));
        if (button.isEnabled()) {
            button.click();
        }
Run Code Online (Sandbox Code Playgroud)

WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.elementToBeClickable(button)).click();
Run Code Online (Sandbox Code Playgroud)

但仍然相同 - submit()工作正常,click() - 没有.

hem*_*nto 5

该方法object.submit()用于将表单提交给服务器.它还有另一个优点,如果你无法找到"提交"按钮,那么你可以获取表单的任何对象并触发submit()函数.似乎在searchButton.submit();searchButton中是表单的一个元素,对它的提交操作会触发在服务器上提交表单.

现在,为什么searchButton.click();不在这里工作可能有以下原因.

  1. 该按钮可见但未启用.
  2. 驱动程序正在查找searchButton元素的2个实例.

建议:评估以下代码并检查它是否返回多个元素.如果是,那么你点击了错误的实例.

List<WebElements> e = driver.findElements(By.xpath("//button[@type='submit']"));
Run Code Online (Sandbox Code Playgroud)

也试试,

driver.findElement(By.xpath(".//button[@class='btn btn__primary'][@type='submit']")).click()
Run Code Online (Sandbox Code Playgroud)

http://docs.seleniumhq.org/docs/03_webdriver.jsp#user-input-filling-in-forms