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

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

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

  1. public class TestBikeInsurancePrice extends HepsterTest {
  2. private void prepareTest() {
  3. initiateBrowserWebShop();
  4. var url = baseUrl + "/fahrradversicherung-test-2020";
  5. driver.get(url);
  6. handleCookie(driver);
  7. }
  8. @Test(priority = 1)
  9. void checkBeschädigung() throws FileNotFoundException {
  10. prepareTest();
  11. List<CsvPrice> stuff = readFromCSV("resources/price/Test Fahrradversicherung Upload.csv");
  12. stuff.forEach(csvPrice -> {
  13. System.out.println(csvPrice.getQualityName() + " " + csvPrice.getCoverageSum() + " " + csvPrice.getDurationTimeUnit() + " " + csvPrice.getDurationRiskPremium());
  14. Select price = new Select(driver.findElement(By.id("coverageSum")));
  15. price.selectByValue(csvPrice.getCoverageSum().toString());
  16. try {
  17. Thread.sleep(1000);
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. String qualityName;
  22. if (csvPrice.getQualityName().equals("Diebstahl")) qualityName = "Nur Diebstahl";
  23. else qualityName = csvPrice.getQualityName();
  24. driver.findElement(By.xpath("//*[contains(text(),'" + qualityName + "')]")).click();
  25. try {
  26. Thread.sleep(1000);
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. String duration;
  31. if (!csvPrice.getDurationTimeUnit().equals("MONTHS")) duration = "Preisvorteil";
  32. else duration = "flexibel, mtl. kündbar";
  33. driver.findElement(By.xpath("//*[contains(text(),'" + duration + "')]")).click();
  34. try {
  35. Thread.sleep(1000);
  36. } catch (InterruptedException e) {
  37. e.printStackTrace();
  38. }
  39. WebElement priceElement = driver.findElement(By.xpath("//*[@id='product-configurator-spinner']//parent::span"));
  40. String priceAsString = priceElement.getText().split(" ")[0];
  41. System.out.println(priceAsString);
  42. Assert.assertEquals(csvPrice.getPriceBasePrice().setScale(2), new BigDecimal(priceAsString.replace(",", ".")).setScale(2));
  43. });
  44. }
wvmv3b1j

wvmv3b1j1#

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

  1. WebDriverWait wait = new WebDriverWait(driver,10);
  2. stuff.forEach(csvPrice -> {
  3. System.out.println(csvPrice.getQualityName() + " " + csvPrice.getCoverageSum() + " " + csvPrice.getDurationTimeUnit() + " " + csvPrice.getDurationRiskPremium());
  4. wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("coverageSum")));
  5. Select price = new Select(driver.findElement(By.id("coverageSum")));
  6. price.selectByValue(csvPrice.getCoverageSum().toString());
  7. String qualityName;
  8. if (csvPrice.getQualityName().equals("Diebstahl")) qualityName = "Nur Diebstahl";
  9. else qualityName = csvPrice.getQualityName();
  10. wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'" + qualityName + "')]")));
  11. driver.findElement(By.xpath("//*[contains(text(),'" + qualityName + "')]")).click();
  12. String duration;
  13. if (!csvPrice.getDurationTimeUnit().equals("MONTHS")) duration = "Preisvorteil";
  14. else duration = "flexibel, mtl. kündbar";
  15. wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'" + duration + "')]")));
  16. driver.findElement(By.xpath("//*[contains(text(),'" + duration + "')]")).click();
  17. wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='product-configurator-spinner']//parent::span")));
  18. WebElement priceElement = driver.findElement(By.xpath("//*[@id='product-configurator-spinner']//parent::span"));
  19. String priceAsString = priceElement.getText().split(" ")[0];
  20. System.out.println(priceAsString);
  21. Assert.assertEquals(csvPrice.getPriceBasePrice().setScale(2), new BigDecimal(priceAsString.replace(",", ".")).setScale(2));
  22. });
展开查看全部
u0njafvf

u0njafvf2#

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

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

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

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

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

  1. //Declare and initialise a fluent wait
  2. FluentWait wait = new FluentWait(driver);
  3. //Specify the timout of the wait
  4. wait.withTimeout(5000, TimeUnit.MILLISECONDS);
  5. //Sepcify polling time
  6. wait.pollingEvery(250, TimeUnit.MILLISECONDS);
  7. //Specify what exceptions to ignore
  8. wait.ignoring(NoSuchElementException.class)
  9. //This is how we specify the condition to wait on.
  10. //This is what we will explore more in this chapter
  11. wait.until(ExpectedConditions.alertIsPresent());

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

展开查看全部

相关问题