java 设置 selenium webdriver 的默认执行速度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32067341/
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-11-02 19:34:51  来源:igfitidea点击:

Set selenium webdriver's default execution speed

javauser-interfaceseleniumselenium-webdriverselenium-ide

提问by Manuel Faria

I'm running some GUI tests with webdriver. I exported some tests directly from selenium IDE. In this test I had to decrease IDE's speed to run it due to the loading of a drop down. How can I slow down my test in Selenium webdriver? I already put

我正在使用 webdriver 运行一些 GUI 测试。我直接从 selenium IDE 导出了一些测试。在这个测试中,由于加载了一个下拉菜单,我不得不降低 IDE 的运行速度。如何在 Selenium webdriver 中减慢我的测试速度?我已经放了

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

and it kept running at a fast speed. I know the sleep option but that's not what I'm looking for, I would like to change the webdriver's default execution speed. Here's my code:

并且一直在高速运转。我知道睡眠选项,但这不是我要找的,我想更改 webdriver 的默认执行速度。这是我的代码:

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ProfileCheck {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private final StringBuffer verificationErrors = new StringBuffer();

@Before
public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "http://localhost:8080";
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
}

@Test
public void testProfileCheck() throws Exception {
    System.out.println("Test if profiles have access to the screen");
    // Administrateur (has access)

    driver.get(baseUrl + "/Dashboard/index.jsp?lang=en");
    driver.findElement(By.cssSelector("input[name=combo_profile]")).click();
    driver.findElement(
            By.cssSelector(".x-boundlist-item:contains('Administrateur')"))
            .click();
    driver.get(baseUrl + "/Params/ClientCutOff/index.jsp?lang=en");
    try {
        assertTrue(driver.getTitle().matches("^[\s\S]*ClientCutOff$"));
    } catch (Error e) {
        verificationErrors.append(e.toString());
    }
    // Habilitation (no access)
    driver.get(baseUrl + "/Dashboard/index.jsp?lang=en");
    driver.findElement(By.cssSelector("input[name=combo_profile]")).click();
    driver.findElement(
            By.cssSelector(".x-boundlist-item:contains('Habilitation')"))
            .click();
    driver.get(baseUrl + "/Params/ClientCutOff/index.jsp?lang=en");
    try {
        assertFalse(driver.getTitle().matches("^[\s\S]*ClientCutOff$"));
    } catch (Error e) {
        verificationErrors.append(e.toString());
    }
}

@After
public void tearDown() throws Exception {

    try {
        Thread.sleep(5000);
        driver.quit();
    } catch (Exception e) {
    }
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
        fail(verificationErrorString);
    }
}

private boolean isElementPresent(By by) {
    try {
        driver.findElement(by);
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}

private boolean isAlertPresent() {
    try {
        driver.switchTo().alert();
        return true;
    } catch (NoAlertPresentException e) {
        return false;
    }
}

private String closeAlertAndGetItsText() {
    try {
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        if (acceptNextAlert) {
            alert.accept();
        } else {
            alert.dismiss();
        }
        return alertText;
    } finally {
        acceptNextAlert = true;
    }
}
}

Read some answers and none helped

阅读一些答案,但没有任何帮助

Decreasing the speed of Selenium Webdriver

降低 Selenium Webdriver 的速度

https://sqa.stackexchange.com/questions/8451/how-can-i-reduce-the-execution-speed-in-webdriver-so-that-i-can-view-properly-wh

https://sqa.stackexchange.com/questions/8451/how-can-i-reduce-the-execution-speed-in-webdriver-so-that-i-can-view-properly-wh

Selenium IDE - Set default speed to slow

Selenium IDE - 将默认速度设置为慢速

回答by Ran Adler

Don't use sleep!!!

不要用sleep!!!

public static WebElement findElement(WebDriver driver, By selector, long timeOutInSeconds) {
    WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
    wait.until(ExpectedConditions.presenceOfElementLocated(selector));

    return findElement(driver, selector);
}

回答by drkthng

Once there was a "setSpeed()" method for the Java bindings of Selenium WebDriver. But it was deprecated, because it makes no sense regarding browser automation.

曾经有一个用于 Selenium WebDriver 的 Java 绑定的“setSpeed()”方法。但它已被弃用,因为它对浏览器自动化毫无意义。

Instead if the driver is "faster" than the loading of your elements or sth similar, you should always make intelligent use of waitsto handle these cases.

相反,如果驱动程序比您的元素或类似内容的加载“更快”,您应该始终明智地使用等待来处理这些情况。

To sum it up, there is currently no option to deliberately slow down executionwithin WebDriver itself. there is no other way currently to explicitly slow down steps of yours other than implement Thread.sleep()

总而言之,目前没有选项可以故意减慢WebDriver 本身的执行速度。除了实现 Thread.sleep() 之外,目前没有其他方法可以显式减慢您的步骤

BUT there are some other options that you might explore:

但是,您可以探索其他一些选项:

For example you could write your own method to click elements if you want to slow down clicking of elements:

例如,如果您想减慢元素的点击速度,您可以编写自己的方法来点击元素:

public void clickElement(WebElement element) {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    element.click();
}

if you wanted to slowdown the findElement method you could write another helper method:

如果您想减慢 findElement 方法的速度,您可以编写另一个辅助方法:

public void findElement(By by) {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    driver.findElement(by);
}

You could even write your own extended class from one of the WebDriver classes as is described herelike this:

你甚至可以从如描述的webdriver类之一编写自己的扩展类这样的:

public class MyFirefoxDriver extends FirefoxDriver {

@Override
public WebElement findElement(By by) {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return by.findElement((SearchContext) this);
}

You could write these methods for all executions that you want to slow down.

您可以为要减慢的所有执行编写这些方法。

回答by Cronax

Under normal circumstances, when it looks for an element, Selenium keeps trying to find an element for up to however long as you've set the value of "implicitly wait". This means that if the element is found sooner than that, it will continue with test execution. I am no expert in Java, but in the code you provide I can't identify any bits that are looking for a drop-down item. Since a drop-down menu can be loaded long before the actual items inside it are loaded, I would wager that therein lies your issue: it's looking for the drop-down itself, finds it, stops waiting and starts trying to execute the rest of the test, which fails because the items weren't loaded yet. The solution therefore would be to look for the specific item you're trying to select. Unfortunately I am not well-versed enough in Java to provide you with the actual code solution.

在正常情况下,当它寻找一个元素时,Selenium 会一直尝试寻找一个元素,只要你设置了“隐式等待”的值。这意味着如果该元素早于找到,它将继续执行测试。我不是 Java 专家,但在您提供的代码中,我无法识别任何正在寻找下拉项的位。由于下拉菜单可以在加载其中的实际项目之前很久就加载,我敢打赌这就是您的问题:它正在寻找下拉菜单本身,找到它,停止等待并开始尝试执行其余部分测试失败,因为项目尚未加载。因此,解决方案是查找您尝试选择的特定项目。

As an aside, in my experience when exporting from Selenium IDE to something else you end up with tests that are almost, but not quite, entirely unlike what you expect. They couldbe doing what you expect them to, but they usually take shortcuts or at least a different approach than you would if you were to code the tests yourself.

顺便说一句,根据我的经验,当从 Selenium IDE 导出到其他东西时,您最终会得到与您期望的几乎但不完全不同的测试。他们可能会做你期望他们做的事情,但他们通常会采取捷径或至少与你自己编写测试代码不同的方法。