本文介绍了文字在网页中出现多少次-Selenium Webdriver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算使用硒webdriver(java)在页面上显示文本"Ex:VIM LIQUID MARATHI"的次数.请帮忙.

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...

推荐答案

使用getPageSource()的问题是,可能有id,类名或代码的其他部分与您的String匹配,但实际上并没有出现在页面上.我建议仅在body元素上使用getText(),它将仅返回页面的内容,而不返回HTML.如果我正确理解了您的问题,那么我认为这正是您想要的.

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);

变量count包含出现的次数.

The variable count contains the number of occurrences.

这篇关于文字在网页中出现多少次-Selenium Webdriver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 11:33