用selenium编写睡眠以加载页面中的元素?

vptzau2j  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(463)

我写了一些代码比较价格从网站与csv文件,我的测试工作良好,但它需要很长的时间(1分钟)。在找到网页中的每一个元素之前,我使用了睡眠。您是否有其他方法编写此测试以更快地运行代码,使用此方法加载每个价格并与csv文件中的价格进行比较需要1秒。另一方面,如果没有睡眠,我的代码将无法工作,因为加载页面和查找元素。

public class TestBikeInsurancePrice extends HepsterTest {    
private void prepareTest() {
        initiateBrowserWebShop();
        var url = baseUrl + "/fahrradversicherung-test-2020";
        driver.get(url);
        handleCookie(driver);
    }

    @Test(priority = 1)
    void checkBeschädigung() throws FileNotFoundException {
        prepareTest();
        List<CsvPrice> stuff = readFromCSV("resources/price/Test Fahrradversicherung Upload.csv");

        stuff.forEach(csvPrice -> {
            System.out.println(csvPrice.getQualityName() + " " + csvPrice.getCoverageSum() + " " + csvPrice.getDurationTimeUnit() + " " + csvPrice.getDurationRiskPremium());
            Select price = new Select(driver.findElement(By.id("coverageSum")));
            price.selectByValue(csvPrice.getCoverageSum().toString());

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            String qualityName;
            if (csvPrice.getQualityName().equals("Diebstahl")) qualityName = "Nur Diebstahl";
            else qualityName = csvPrice.getQualityName();
            driver.findElement(By.xpath("//*[contains(text(),'" + qualityName + "')]")).click();

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            String duration;
            if (!csvPrice.getDurationTimeUnit().equals("MONTHS")) duration = "Preisvorteil";
            else duration = "flexibel, mtl. kündbar";
            driver.findElement(By.xpath("//*[contains(text(),'" + duration + "')]")).click();

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            WebElement priceElement = driver.findElement(By.xpath("//*[@id='product-configurator-spinner']//parent::span"));
            String priceAsString = priceElement.getText().split(" ")[0];
            System.out.println(priceAsString);
            Assert.assertEquals(csvPrice.getPriceBasePrice().setScale(2), new BigDecimal(priceAsString.replace(",", ".")).setScale(2));
        });
    }
wvmv3b1j

wvmv3b1j1#

显式等待:对于命令式、过程式语言,selenium客户端可以使用显式等待。它们允许您的代码暂停程序执行或冻结线程,直到您传递的条件解决为止。以特定频率调用条件,直到等待超时结束。这意味着只要条件返回错误值,它就会继续尝试和等待。
我在代码中添加了显式等待。

WebDriverWait wait = new WebDriverWait(driver,10);

stuff.forEach(csvPrice -> {
            System.out.println(csvPrice.getQualityName() + " " + csvPrice.getCoverageSum() + " " + csvPrice.getDurationTimeUnit() + " " + csvPrice.getDurationRiskPremium());
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("coverageSum")));
            Select price = new Select(driver.findElement(By.id("coverageSum")));
            price.selectByValue(csvPrice.getCoverageSum().toString());

            String qualityName;
            if (csvPrice.getQualityName().equals("Diebstahl")) qualityName = "Nur Diebstahl";
            else qualityName = csvPrice.getQualityName();
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'" + qualityName + "')]")));
            driver.findElement(By.xpath("//*[contains(text(),'" + qualityName + "')]")).click();

            String duration;
            if (!csvPrice.getDurationTimeUnit().equals("MONTHS")) duration = "Preisvorteil";
            else duration = "flexibel, mtl. kündbar";
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'" + duration + "')]")));
            driver.findElement(By.xpath("//*[contains(text(),'" + duration + "')]")).click();

            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='product-configurator-spinner']//parent::span")));
            WebElement priceElement = driver.findElement(By.xpath("//*[@id='product-configurator-spinner']//parent::span"));
            String priceAsString = priceElement.getText().split(" ")[0];
            System.out.println(priceAsString);
            Assert.assertEquals(csvPrice.getPriceBasePrice().setScale(2), new BigDecimal(priceAsString.replace(",", ".")).setScale(2));
        });
u0njafvf

u0njafvf2#

使用时的实际问题: Thread.sleep() thread.sleep()被认为是显式等待的最坏情况,因为它必须等待指定为thread.sleep(3000)参数的完整时间,然后才能继续。
结果,下一步不得不等待整个过程结束。
解决方案:更改 Thread.sleep() 进入 explicit wait .
在selenium中,在这种情况下,“等待”很方便,或者在执行测试时扮演重要角色。
selenium中有三种类型的wait。
隐式等待:在隐式等待中,webdriver在试图查找任何元素时轮询dom一段时间。当网页上的某些元素不能立即使用并且需要一些时间来加载时,这可能非常有用。
代码:

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

显式等待显式等待允许我们的代码暂停程序执行或冻结线程,直到您传递的条件解决为止。以特定频率调用条件,直到等待超时结束。这意味着只要条件返回错误值,它就会继续尝试和等待。
代码:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("YOUR-LOCATOR")));

fluentwait:fluentwait示例定义等待条件的最长时间,以及检查条件的频率。
代码:

//Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
//Specify the timout of the wait
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
//Sepcify polling time
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
//Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)

//This is how we specify the condition to wait on.
//This is what we will explore more in this chapter
wait.until(ExpectedConditions.alertIsPresent());

裁判:
https://www.selenium.dev/documentation/en/webdriver/waits/
https://www.browserstack.com/guide/wait-commands-in-selenium-webdriver

相关问题