简体   繁体   中英

How many times a text appears in webpage - Selenium Webdriver

Hi I would like to count how many times a text Ex: "VIM LIQUID MARATHI" appears on a page using selenium webdriver(java). Please help.

I have used the following to check if a text appears in the page using the following in the main class

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

and a function to return a boolean

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

... but do not know how to count the number of occurrences...

The problem with using getPageSource() , is there could be id's, classnames, or other parts of the code which match your String, but those don't actually appear on the page. I suggest just using getText() on the body element, which will only return the page's content, and not HTML. If I'm understanding your question correctly, I think that is more what you are looking for.

// 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());
}
System.out.println(count);

The variable count contains the number of occurrences.

There are two different ways to do this:

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

This will tell the driver to find all of the elements that have the text, and then output the size.

The second way is to search the HTML, like you said.

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

This will get the page source, the split the string whenever it finds the match, then counts the number of splits it made.

You can try to execute javascript expression using webdriver:

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

If you are using jQuery on your page you can use jQuery's selectors:

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

[proper selector] - this should be selector that will match text you are searching for.

尝试

int size = driver.findElements(By.partialLinkText("VIM MARATHI")).size();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM