2013-08-26 41 views
1

嗨,我想計算一下,使用selenium webdriver(java)在一個頁面上顯示文本的次數:「VIM LIQUID MARATHI」。請幫忙。一個文本在網頁上出現多少次 - Selenium Webdriver

我已經使用了以下檢查文本使用出現在頁面的主類

assertEquals(true,isTextPresent("VIM LIQUID MARATHI"));

和功能下面是返回一個boolean

protected boolean isTextPresent(String text){ 
    try{ 
     boolean b = driver.getPageSource().contains(text); 
     System.out.println(b); 
     return b; 
    } 
    catch(Exception e){ 
     return false; 
    } 
} 

..但不知道如何統計出現次數...

+1

你必須向我們展示了一些努力。你嘗試了什麼? – LaurentG

+0

我試過driver.getPageSource()。contains(text);但是無論文本是否存在,它都會輸出一個布爾值。我試過selenium.getXpathCount,但那不是我正在尋找的... –

+0

它總是出現在某些元素中嗎?我是否總是在'span'元素中?爲什麼你需要這個? – Arran

回答

4

使用getPageSource()的問題是,可能存在與您的字符串匹配的代碼的id,classnames或其他部分,但實際上並未出現在頁面上。我建議在body元素上使用getText(),它只返回頁面的內容,而不是HTML。如果我正確理解你的問題,我認爲這更符合你的需求。

// get the text of the body element 
WebElement body = driver.findElement(By.tagName("body")); 
String bodyText = body.getText(); 

// count occurrences of the string 
int count = 0; 

// search for the String within the text 
while (bodyText.contains("VIM LIQUID MARATHI")){ 

    // when match is found, increment the count 
    count++; 

    // continue searching from where you left off 
    bodyText = bodyText.substring(bodyText.indexOf("VIM LIQUID MARATHI") + "VIM LIQUID MARATHI".length()); 
} 

變量count包含出現次數。

0

您可以嘗試使用webdriver執行javascript表達式:

((JavascriptExecutor)driver).executeScript("yourScript();"); 

如果您在您的網頁上使用jQuery你可以使用jQuery的選擇:

((JavascriptExecutor)driver).executeScript("return jQuery([proper selector]).size()"); 

[適當的選擇 - 這應該是選擇將匹配您正在搜索的文本。

5

有兩種不同的方式來做到這一點:

int size = driver.findElements(By.xpath("//*[text()='text to match']")).size(); 

這將告訴司機找到所有具有文本,然後輸出大小的元素。

第二種方法是搜索HTML,就像你說的。

int size = driver.getPageSource().split("text to match").length-1; 

這將讓網頁的源文件,拆分只要找到匹配的字符串,然後計算它使分割的數量。

+0

很好的答案。簡單而簡單 –

0

嘗試

int size = driver.findElements(By.partialLinkText("VIM MARATHI")).size(); 
相關問題