您好我想计算一下文本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;
}
}
...但不知道如何计算出现次数......
答案 0 :(得分:6)
使用getPageSource()
的问题是,可能有id,classnames或代码中与String匹配的其他部分,但这些部分实际上并不出现在页面上。我建议在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());
}
System.out.println(count);
变量count
包含出现次数。
答案 1 :(得分:5)
有两种不同的方法可以做到这一点:
int size = driver.findElements(By.xpath("//*[text()='text to match']")).size();
这将告诉驱动程序找到包含该文本的所有元素,然后输出大小。
第二种方法是搜索HTML,就像你说的那样。
int size = driver.getPageSource().split("text to match").length-1;
这将获取页面源,每当找到匹配时拆分字符串,然后计算它所做的拆分数。
答案 2 :(得分:0)
您可以尝试使用webdriver执行javascript表达式:
((JavascriptExecutor)driver).executeScript("yourScript();");
如果您在页面上使用jQuery,则可以使用jQuery的选择器:
((JavascriptExecutor)driver).executeScript("return jQuery([proper selector]).size()");
[正确的选择器] - 这应该是与您要搜索的文本匹配的选择器。
答案 3 :(得分:0)
尝试
int size = driver.findElements(By.partialLinkText("VIM MARATHI")).size();