【问题标题】:Unable to click the link using selenium webdriver Version 3.0.0.beta3使用 selenium webdriver 版本 3.0.0.beta3 无法单击链接
【发布时间】:2017-02-03 03:26:19
【问题描述】:

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

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

我正在使用:

操作系统: Win10

Slenium WebDriver: 版本 3.0.0.beta3

火狐浏览器版本: 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();
    }   
}

【问题讨论】:

    标签: java selenium selenium-webdriver webdriver


    【解决方案1】:

    这真的很奇怪。这个页面有些地方在页面完全加载之前不允许点击......它会进行初始加载,然后触发第二次广告加载。如果没有等待,我找不到点击该链接的方法。可能还有另一种方法可以做到这一点,但我想不出怎么做。下面的代码对我有用(但很难看)。

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

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

    【讨论】:

    • 我可以使用您建议的上述代码点击“登录”链接。
    【解决方案2】:

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

        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");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-10
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 2016-08-03
      相关资源
      最近更新 更多