Java 让 Selenium 暂停 X 秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20009211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:18:15  来源:igfitidea点击:

Getting Selenium to pause for X seconds

javaseleniumselenium-webdriver

提问by user2612619

What I am trying to accomplish is browsing to a page, waiting for something to load and then taking and saving a screenshot.

我想要完成的是浏览到一个页面,等待加载某些内容,然后截取并保存屏幕截图。

The code I already have is

我已经拥有的代码是

WebDriver driver = new FirefoxDriver();


driver.get("http://www.site.com");


driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

try {

    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("/home/Desktop/image.png"));

} catch (Exception e) { 

       e.printStackTrace(); 
}

driver.close();

The reason I need to wait, even if the page is loaded is because it'll be loaded but on the site the content I'd like to take a picture of loads after a few seconds. For some reason the page is not waiting, is there another method that I can use to get the driver/page to wait for X amount of seconds?

我需要等待的原因,即使页面已加载,也是因为它将被加载,但在网站上,我想在几秒钟后拍摄加载的图片。由于某种原因页面没有等待,是否有另一种方法可以让驱动程序/页面等待 X 秒?

采纳答案by user2612619

You can locate an element that loads after the initial page loads and then make Selenium wait until that element is found.

您可以找到在初始页面加载后加载的元素,然后让 Selenium 等待直到找到该元素。

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ID")));

回答by Jas

That wouldnt really be a selenium specific thing. You just want java to sleep for a bit after loading the page but before taking the screenshot.

那不会真的是硒特定的东西。您只希望 java 在加载页面后但在截取屏幕截图之前休眠一会儿。

Thread.sleep(4000);

put that after your driver.get statement.

把它放在你的 driver.get 语句之后。

回答by Petr Mensik

Just in case it will help somebody, you should always try to avoid implicit waits and especially Thread#sleepas much as you can. If you do Thread.sleep(10), your code will alwayswait for 10 seconds even in case your page is ready after 1 sec. So this can slow your tests substantially if you use this often.

以防万一它会对某人有所帮助,您应该始终尽量避免隐式等待,尤其是Thread#sleep尽可能多地。如果您这样做Thread.sleep(10),即使您的页面在 1 秒后准备就绪,您的代码也将始终等待 10 秒。因此,如果您经常使用它,这会大大减慢您的测试速度。

Better way is to use ExplicitWaitswhich you means you will wait exactly as long as some action happens or some element gets rendered on the page. So in your case, I would use explicit wait to check whether is everything loaded and then take a screenshot.

更好的方法是使用ExplicitWaits,这意味着只要某些操作发生或某些元素在页面上呈现,您就会等待。因此,在您的情况下,我将使用显式等待来检查是否已加载所有内容,然后截取屏幕截图。

回答by JohnP2

If you want to delay a certain number of seconds, rather than to respond as soon as possible, here is a function for pause similar to what selenium IDE offers:

如果你想延迟一定的秒数,而不是尽快响应,这里有一个类似于 selenium IDE 提供的暂停功能:

public void pause(Integer milliseconds){
    try {
        TimeUnit.MILLISECONDS.sleep(milliseconds);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

source

来源

回答by user3605834

const { By, until } = require('selenium-webdriver');


this.wait = async function (amount: number) {
      try {
        await this.driver.wait(
          until.elementLocated(By.css('[data-test-id="does-not-exist"]')),
          amount,
          'Looking for element'
        );
      } catch (e) {
        console.log('waiting')
      }

We look for a css identifier that isn't there for x amount of seconds. This is typescript btw. This would be a method on some relevant class, or a function by itself. Use it like this

我们寻找一个在 x 秒内不存在的 css 标识符。这是打字稿顺便说一句。这将是某个相关类上的一个方法,或者是一个函数本身。像这样使用它

  const button = await this.findByCSSSelector('[data-test-id="get-quote-button"]')
  const actions = this.driver.actions({ bridge: true }); 
  await actions.move({origin: button }).perform();

  // Small pause to observe animation is working correctly in all browsers
  await this.wait(700)

  const carat = await this.findByCSSSelector('[data-test-id="carat"]');

This waits for .7 of a second so that you can see that whatever animation is working in your functional tests.

这将等待 0.7 秒,以便您可以看到功能测试中正在运行的任何动画。

回答by Ashish Khare

The most simple of all.

最简单的。

Just try this and forget rest! The equivalent of this code can be used in any language. I am writing this in python.

试试这个,忘记休息!此代码的等价物可用于任何语言。我正在用python写这个。

import time
time.sleep(2)

this will make the compiler go to sleep for 2 seconds.

这将使编译器进入睡眠状态 2 秒。