无法使用selenium webdriver版本3.0.0.beta3单击该链接

时间:2016-09-25 20:55:05

标签: java selenium selenium-webdriver webdriver

我已经编写了以下Junit代码,点击下面 quikr 网站上的 Sign In 链接 的 http://www.quikr.com/

代码运行正常,没有任何错误,但webdriver似乎没有点击网站上的 Sign In 链接。请建议。

我正在使用:

操作系统: Win10

Slenium WebDriver:版本3.0.0.beta3

Firefox浏览器版本: 49.0.1

import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Quikr {
    @Test
    public void loginTest(){
        System.setProperty("webdriver.gecko.driver","C:\\Eclipse\\Drivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.quikr.com/");
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
         if(!driver.findElements(By.xpath(".//*[@id='responsiveHeader']/div[1]/div[1]/ul/li[4]/a/span[1]")).isEmpty()){
             System.out.println("Link present");
         }else{
             System.out.println("Link not present");
         }
        driver.findElement(By.xpath(".//*[@id='responsiveHeader']/div[1]/div[1]/ul/li[4]/a/span[1]")).click();
    }   
}

2 个答案:

答案 0 :(得分:1)

这是一个非常奇怪的。关于此页面的某些内容在页面完全加载之前不允许点击...并且它会执行初始加载,然后触发第二批广告。我无法在没有大量等待的情况下找到点击该链接的方法。可能有另一种方法可以做到这一点,但我无法想到如何做到这一点。下面的代码对我有用(但很难看)。

driver.get("http://www.quikr.com/");
Thread.sleep(10000);
driver.findElement(By.cssSelector("span.sign-in")).click();

使用Thread.sleep()不是一个好习惯,99%的情况都应避免使用。 WebDriverWait是等待元素等的首选方式。

答案 1 :(得分:0)

我认为你得到了答案,但我会添加一个动态等待时间,而不是作为答案给出的硬编码等待时间。您可以在按下所需按钮之前使用此方法。

    public static void waitForPageToLoad(long timeOutInSeconds) {
    System.out.println("Waiting for page to load");
    ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
        }
    };
    try {
        System.out.println("Waiting for page to load...");
        WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
        wait.until(expectation);
    } catch (Throwable error) {
        System.out.println(
                "Timeout waiting for Page Load Request to complete after " + timeOutInSeconds + " seconds");
    }
}