2016-05-23 85 views
0

考慮以下實現:調試腳本 - 硒的webdriver

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(int i=75;i<79;i++),那麼它工作正常。

我想初始化我的列表以外的循環,以便我可以限制它到我的列表的大小。一種方法是用另一個名字製作另一個列表。但這是最好的選擇嗎?

回答

0

我將設定用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); 

    ... 
}