Nan*_*shi 2 java selenium selenium-webdriver
嗨,我想计算一下文本Ex:"VIM LIQUID MARATHI"出现在页面上使用selenium webdriver(java)多少次.请帮忙.
我使用以下内容检查主要类中使用以下内容是否在页面中显示文本
assertEquals(true,isTextPresent("VIM LIQUID MARATHI"));
和一个返回布尔值的函数
protected boolean isTextPresent(String text){
try{
boolean b = driver.getPageSource().contains(text);
System.out.println(b);
return b;
}
catch(Exception e){
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
...但不知道如何计算出现次数......
使用的问题getPageSource()
是,可能有id,classnames或代码的其他部分与您的String匹配,但这些部分实际上并不出现在页面上.我建议只使用getText()
body元素,它只返回页面的内容,而不是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());
}
System.out.println(count);
Run Code Online (Sandbox Code Playgroud)
该变量count
包含出现次数.
有两种不同的方法可以做到这一点:
int size = driver.findElements(By.xpath("//*[text()='text to match']")).size();
Run Code Online (Sandbox Code Playgroud)
这将告诉驱动程序找到包含该文本的所有元素,然后输出大小.
第二种方法是搜索HTML,就像你说的那样.
int size = driver.getPageSource().split("text to match").length-1;
Run Code Online (Sandbox Code Playgroud)
这将获取页面源,每当找到匹配时拆分字符串,然后计算它所做的拆分数.
归档时间: |
|
查看次数: |
10588 次 |
最近记录: |