在硒中等几秒钟?

时间:2014-11-25 06:59:30

标签: java selenium selenium-webdriver

我已经编写了一个selenium代码来选择浏览器上的按钮并单击它但我希望selenium在移动到该元素时等待几秒钟。我该怎么做?以下是我尝试过的代码,但它确实对我不起作用。

我的代码:

    Actions actionobj = new Actions(fd1);       
    actionobj.moveToElement(heatmap);
    actionobj.perform();    
    fd1.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);   
    Actions action2 = new Actions(fd1);     
    action2.click(heatmap);
    action2.perform();

我的代码工作正常,但是当鼠标移动到按钮时它停止了10秒。我也尝试过Thread.sleep(),但这也没有用。

5 个答案:

答案 0 :(得分:4)

Java Selenium API似乎有一个方法pause(long)

根据文档,它需要long表示暂停的毫秒数。

   Actions actionobj = new Actions(fd1);        
    actionobj.moveToElement(heatmap);
    actionobj.pause(10000); //wait 10 seconds
    actionobj.click(heatmap);
    actionobj.perform();

imlicitlyWait()不会暂停您的代码。如果没有立即找到WebElement,这是一种让Selenium总是等待几秒钟的方法。

请注意,pause()已弃用。手动暂停代码是不好的做法。您应该问自己为什么认为有必要暂停代码。如果你想模拟一个等待10秒的人,那就完全没问题,如果你想要一些其他的元素或javascript来完成加载,那么你应该考虑使用不同的方法。

编辑:你的代码不会中途暂停(即使你使用Thread.sleep()),因为在Action.perform()执行整个序列,因为你首先构建了Actions对象,然后在执行时,你执行整个行动的整个过程。

答案 1 :(得分:2)

您也可以尝试这种方式,

Actions actionobj = new Actions(fd1);
actionobj.moveToElement(heatmap).build().perform();
Thread.sleep(10000); 
actionobj.click(heatmap).build().perform();

答案 2 :(得分:1)

这是因为perform()调用是执行操作的地方。在这里,您需要先为moveToElement()创建两个操作并执行操作。然后创建单击操作并执行操作。

希望这会有所帮助。如果这不是您想要的,或者您的意思不同,请发表评论。

答案 3 :(得分:1)

尝试使用此代码突出显示并单击该元素而不是暂停该元素,这对您的问题来说不是一个可行的解决方案:

//highlighting the element on which action will be performed
    public static void highlightElement(WebDriver driver, WebElement element) {

        try
        {
            for (int i = 0; i < 3; i++) 
            {
                JavascriptExecutor js = (JavascriptExecutor) driver;
                js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "color: red; border: 2px solid red;");
            } 

        }
        catch(Throwable t)
        {
            System.err.println("Error came : " +t.getMessage());
        }
    }

注意:以上代码将突出显示元素,即,将围绕&#34;红色&#34;色块。你必须通过&#34;驱动程序&#34;和&#34; webelement&#34;作为参数。

您可以直接从主类调用此方法。并且,根据您的上述代码,您可以传递这样的元素:

highlightElement(driver,heatmap);

答案 4 :(得分:-1)

如果您只想等待几秒钟,(只是为了让用户了解正在发生的事情),那么可以通过暂停java线程轻松实现。

添加强制等待的方法有很多种。

这是通过使用简单的java(与Selenium无关)

Thread.sleep(<<timeInMilliSeconds>>);

希望这适合你。

相关问题