【问题标题】:Debugging script run in for loop - Selenium WebDriver在 for 循环中运行的调试脚本 - Selenium WebDriver
【发布时间】:2016-05-23 23:44:34
【问题描述】:

考虑以下实现:

WebDriverWait wait = new WebDriverWait(driver, 60);
List<WebElement> countryLinks = driver.findElements(By.cssSelector("a[href*='/country/']"));
for (int i = 75; i < countryLinks.size(); i++) {
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a[href*='/country/']")));
    Thread.sleep(1000);
    WebElement elem = countryLinks.get(i);

    JavascriptExecutor js = (JavascriptExecutor) driver;
    //this line will scroll to element.
    js.executeScript("window.scrollTo(" + elem.getLocation().x + "," + (elem.getLocation().y - 100) + ");");

    System.out.println("The Country is: " + elem.getText());
    elem.click();
    wait.until(ExpectedConditions.visibilityOfElementLocated(countryDetailVerify));
    driver.navigate().back();
}

当 i = 75 时,上面的脚本只运行一次。但是当我在 for 循环中初始化列表并将 for 循环更改为 for(int i=75;i&lt;79;i++) 时,它可以正常工作。

我想在 for 循环之外初始化我的列表,以便我可以将其限制为我的列表的大小。一种方法是制作另一个具有不同名称的列表。但这是最好的选择吗?

【问题讨论】:

    标签: java selenium-webdriver


    【解决方案1】:

    我会用 XPath 在定位器中设置索引,然后循环直到没有更多元素:

    for(int i = 75; ; i++) {
        List<WebElement> countryLinks = driver.findElements(
            By.xpath("(//a[contains(@href, '/country/')])[{0}]".format(i)));
    
        if (countryLinks.size() == 0)
          break;
    
        WebElement countryLink = countryLinks.get(0);
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多