Selenium向我显示一个禁用的按钮,为什么?

时间:2015-09-29 15:53:12

标签: java selenium

我有这个示例代码:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class App {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new HtmlUnitDriver();
        driver.get("http://www.hepsiburada.com");
        WebElement element = driver.findElement(By.xpath("//*[@id=\"tabBestSelling\"]/div/div/div/div/div/ul/li[1]/div/a"));
        element.click();
        System.out.println("Page title is: " + driver.getTitle());
        element = driver.findElement(By.xpath("//*[@id=\"addToCart\"]"));
        System.out.println(element);
        driver.quit();
    }
}

当我运行此代码时,元素将打印为:

<button type="button" class="btn m button" id="addToCart" data-catalogname="Telefon" data-isvariants="true" disabled="disabled" data-bind="click: $parent.addCurrentItemToCart.bind($parent), attr:{'data-price':webtrekkCost, 'data-sku':sku, 'data-loginstatus':webtrekkLoginStatus}">

我不明白为什么禁用此按钮?当我使用浏览器导航到同一页面时,该按钮未被禁用。

示例页面:http://www.hepsiburada.com/htc-one-m8-p-TELCEPHTCM8-G

修改

我也尝试过:

    WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"addToCart\"]")));

哪个不起作用......我得到超时..

3 个答案:

答案 0 :(得分:1)

按钮被禁用,因为它具有属性disabled =“disabled”,它显示的方式是因为它以这种方式实现,f.e。

{{1}}

答案 1 :(得分:0)

也许它与HTMLUnitDriver有关?下面的代码对我来说很好。

WebDriver driver = new FirefoxDriver();
driver.get("http://www.hepsiburada.com/");
driver.findElement(By.cssSelector("#tabBestSelling a")).click();
System.out.println("Page title is: " + driver.getTitle());
driver.findElement(By.id("addToCart")).click();

答案 2 :(得分:0)

在html源代码中,如果您看到IE9的按钮具有属性disabled =“disabled”。 HtmlUnitDriver可能将其视为IE9,因此您可以尝试将BrowserVersion更改为FIREFOX_38

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import com.gargoylesoftware.htmlunit.BrowserVersion;

public class Issue5 {

    public static void main(String[] args) throws InterruptedException {

        WebDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_38, true);

        driver.get("http://www.hepsiburada.com");
        WebElement element = driver
                .findElement(By.xpath("//*[@id=\"tabBestSelling\"]/div/div/div/div/div/ul/li[1]/div/a"));
        element.click();
        System.out.println("Page title is: " + driver.getTitle());
        element = driver.findElement(By.xpath("//*[@id=\"addToCart\"]"));
        System.out.println(element);
        element.click();
        driver.quit();
    }

}