我已經分配了一個導航到Google的任務,執行搜索並獲得第一個結果頁面中所有結果的標題。在循環瀏覽通過findElements找到的WebElements時跳過了列表索引
我用findElements
與xpath和試圖循環通過每個結果和driver.navigate().back()
。它拋出了StaleElementReferenceException
,我寫了一個try-catch塊並開始初始化catch塊中的findElements
。
雖然試圖獲得我的findElements的大小(),它被確定爲9時,我用了一個隱含的等待。使用一個明確的,並且Thread.sleep和size()確實設置爲13 - 這正是我期待的。
當一切進展良好時,我可以看到索引在6到12之後跳過。我無法弄清楚發生了什麼。有人能告訴我哪裏出錯了嗎?謝謝!
下面是我的代碼:
@BeforeClass
public void setup() {
driver = LoadWebDriver.getWebDriver();
}
@Test(priority=0)
public void navigateTo() {
driver.manage().window().maximize();
driver.get("https://www.google.co.in/");
}
@Test(priority=1)
public void getTheTitles() throws InterruptedException {
String xPath = "//h3/a";
int a = 0;
boolean loopThru = true;
driver.findElement(By.id("lst-ib")).sendKeys("Java",Keys.ENTER);
// WebDriverWait wait = new WebDriverWait(driver, 10);
// wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(xPath)));
// Thread.sleep(3000);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
List<WebElement> dan = driver.findElements(By.xpath(xPath));
System.out.println("** The fucking size is "+dan.size()+" **");
while(loopThru) {
try {
dan = driver.findElements(By.xpath(xPath));
for (int i = a; i < dan.size(); i++) {
if(i==dan.size()-1){
loopThru=false;
}
dan.get(a).click();
String theTitle = driver.getTitle();
System.out.println(a+" "+theTitle);
driver.navigate().back();
}
}
catch(Exception e) {
a++;
dan = driver.findElements(By.xpath(xPath));
loopThru = true;
}
}
}
@AfterClass
public void tearDown() {
driver.close();
}
看看這個答案可能會幫助你http://stackoverflow.com/questions/41999207/not-able-to-get-links-of-all-the-total-pages/42001030#42001030 – NarendraR