【问题标题】:How can I click on a button using Selenium WebDriver with Java?如何在 Java 中使用 Selenium WebDriver 单击按钮?
【发布时间】:2012-08-23 23:01:15
【问题描述】:

以下是按钮的HTML代码:

<span>
<button class="buttonLargeAlt" onclick="javascript:submitCheckout(this.form);"type="submit">Checkout</button>
</span>

我试过driver.findElement(By.xpath("//span[contains(.,'Checkout')]")).click();

它不工作......

还有其他想法吗?页面上有2个同名按钮。

【问题讨论】:

    标签: java selenium selenium-webdriver automated-tests


    【解决方案1】:
    driver.submit()
    

    应该可以。 如果 DOM 中按钮的顺序始终相同,这也应该有效:

    driver.findElements(By.className("buttonLargeAlt")).get(0).click();
    

    如果它是您页面上的第一个 buttonLargeAlt 按钮。

    【讨论】:

      【解决方案2】:

      试试:

      //span/button[text()='Checkout' and @class='buttonLargeAlt']
      

      //span/button[text()='Checkout'][1]
      

      另外,如果你知道需要点击这两个按钮中的哪一个,你可以试试:

      //span/button[text()='Checkout'][1]
      

      其中[1] 是找到的第一个带有'Checkout' 文本的按钮

      【讨论】:

        【解决方案3】:

        以下应该有效:

        driver.findElement(By.className("buttonLargeAlt")).click();
        driver.findElement(By.xpath("//button[contains(@class='buttonLargeAlt')]")).click();
        driver.findElement(By.xpath("//button[@class='buttonLargeAlt']")).click();
        

        【讨论】:

          【解决方案4】:
              You can achieve this by using XPath with html input element id or by name
              //1. By XPath indexing option:  
              WebElement loginButtonId = 
              driver.findElement(By.xpath("//*[@id='login']"));
              //Xpath of login button i have get For firefox browser
          
              loginButtonId.click();
          
              I hope this work for you
          

          【讨论】:

            【解决方案5】:

            我有添加附件按钮:

            我用这段代码试过了:

            driver.findElement(By.xpath("//*[@id=\"attachments\"]/div/div/img")).sendKeys("C:\\Users\\NayazPasha\\Desktop\\Ndin selenium Testing outputs\\Collab Schedule onclick.png");
            

            【讨论】:

              【解决方案6】:

              XPath 只会获取跨度,而不是物理按钮。

              在这里工作得很好:

              //span[contains(.,'Checkout')]/button
              

              或 By.CssSelector:

              button.buttonLargeAlt
              

              如果仍然不起作用,请解释更多。它在 iFrame 中吗? Selenium 给出了什么错误?

              【讨论】:

              • 或者那个是的 :) 如您所见,查找元素的方法有很多。
              猜你喜欢
              • 1970-01-01
              • 2016-01-30
              • 1970-01-01
              • 2021-11-09
              • 2020-09-04
              • 2019-12-14
              • 1970-01-01
              • 2020-01-24
              • 1970-01-01
              相关资源
              最近更新 更多