繁体   English   中英

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

[英]Unable to click the link using selenium webdriver Version 3.0.0.beta3

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

代码运行良好,没有任何错误,但 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();
    }   
}

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

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

使用Thread.sleep()不是一个好习惯,应该在 99% 的场景中避免使用。 WebDriverWait是等待元素等的首选方式。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM