2014-08-28 68 views
0

我正在使用HTMLUnitDriver進行數據提取。我有一張桌子,裏面放着更多頁面。第1頁共有24條結果,第2頁同樣包含24條結果,第3頁共有2條結果,全部爲50條結果。我遇到的問題是,當我嘗試從頁面獲取所有行時,可能無法獲得全部(24行),我可以獲得小於24的任何數字,這是我不想要的。我總是想要24行,除了最後一頁少於24行。Selenium Webdriver跳過表中的行

在表中的行有以下形式:

<tr id="row28984" class="line_1" onclick="selectRow(28984);Field.activate('qty28984')"> 
<tr id="row93700" class="line_2" onclick="selectRow(93700);Field.activate('qty93700')"> 

我使用的XPath採取他們:

xpath1: //*[@id='resultTable']/tbody/tr 
xpath2: /html/body/center/table/tbody/tr[3]/td/form/table[2]/tbody/tr 

我也用cssSelector這樣的:

webDriver.findElements(By.cssSelector(".line_1,.line_2") 

但沒有任何我嘗試過的工作。我也試圖等待頁面完全加載:

webDriver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS) 

並試圖等待行加載,但沒有任何更改。

我認爲它可能工作的一件事是把Thread.sleep(1000),但我不想這樣做,因爲它不是我的最佳做法,我想使用由Selenium Webdriver提供的東西。

有沒有解決我的問題?

回答

0

嘗試替代Thread.sleep - fluentWait: fluentWait函數返回找到的Web元素。從fluentWait上的文檔:可以實時配置其超時和輪詢間隔的Wait接口的實現。每個FluentWait實例都定義了等待條件的最長時間以及檢查條件的頻率。此外,用戶可以配置等待,以在等待時忽略特定類型的異常,例如在頁面上搜索元素時的NoSuchElementExceptions。 硒的不同等待類型的基本想法,你可以得到here in details

fluentWait函數的使用(呼叫):

public WebElement fluentWait(final By locator) { 
     Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) 
     .withTimeout(30, TimeUnit.SECONDS) 
     // .pollingEvery(5, TimeUnit.SECONDS) 
     .pollingEvery(1, TimeUnit.SECONDS) 
     // .ignoring(NoSuchElementException.class); 
     .ignoring(org.openqa.selenium.NoSuchElementException.class); 

     WebElement foo = wait.until(
       new Function<WebDriver, WebElement>() { 
      public WebElement apply(WebDriver driver) { 
       return driver.findElement(locator); 
      } 
     } 
     ); 
     return foo; 
    } 

注:它是由用於調整輪詢時間間隔。

因此,對於你來說,我會嘗試以下方法:

String elem1Selector="tr[id*=\"row\"][class=\"line_1\"]"; 
String elemt2Selector="tr[id*=\"row\"][class=\"line_2\"]"; 

方法1

//下一步就是申請流利的等待:

elem1=fluentWait(By.cssSelector(elem1Selector)); 
elem2=fluentWait(By.cssSelector(elem1Selector)); 

方法2 另外我們可以嘗試在這裏使用顯式的等待機制,它在這種方式:

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds); 
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>)); 

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>)); 

投射到你的餐桌它像:

wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(elem1Selector))); 

希望這有助於你。

+0

感謝您的答案,但它並沒有解決我的問題。 :(如果你定義你的選擇是,你會得到所有行的表的webdriver的還是跳過某些行。 – user1849859 2014-08-28 21:36:41

+0

。 如 <表類=「用戶」> ​​ 列表 tableRows = driver.findElements(By.cssSelector(「。users tr」) 這將獲得可見頁面上的每個表格行。 – bcar 2014-08-29 03:25:32

0

您是否試圖等待硒捕獲的行數爲24?

long startTime = System.currentTimeMillis(); 
    do { 
      int size=driver.findElements(By.xpath("//*[@id='resultTable']/tbody/tr")).size(); 
      if(size>24) 
       break; 
     }while(System.currentTimeMillis()-startTime<10000); 

您可以調整等待while語句的時間。