使用 Selenium 和 Java 单击按钮

Clicking button with Selenium and Java

我目前正在做一个项目,我可以 select 所有元素,但它确实令人沮丧,代码如下

<a class="btn btn-default button button-medium" href="http://automationpractice.com/index.php?controller=order" title="Proceed to checkout" rel="nofollow">
                        <span>
                            Proceed to checkout<i class="icon-chevron-right right"></i>
                        </span>
                    </a>

我试过xpath, css, linktext, title 等方法都没有成功,如有帮助将不胜感激

我用过的 xpath 示例

driver.findElement(By.xpath("/html//div[@id='layer_cart']//a[@title='Proceed to checkout']/span")).click();

例子css我用过

driver.findElement(By.cssSelector("a[title='Proceed to checkout'] > span")).click();

您可以在按钮上使用图标 CSS:

.icon-chevron-right right

或 xpath:

//i[@class='icon-chevron-right right']

要在元素上 click() 您可以使用以下任一项 :

  • cssSelector:

    driver.findElement(By.cssSelector("a.btn.btn-default.button.button-medium[title='Proceed to checkout'] > span")).click();
    
  • xpath:

    driver.findElement(By.xpath("//a[@class='btn btn-default button button-medium' and @title='Proceed to checkout']/span")).click();
    

理想情况下 click() 在您需要为 elementToBeClickable() 引入 的元素上,您可以使用以下任一方法 :

  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.btn.btn-default.button.button-medium[title='Proceed to checkout'] > span"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='btn btn-default button button-medium' and @title='Proceed to checkout']/span"))).click();