Java 如何找到WebElement在HTMLDOM中出现的次数?

Java 如何找到WebElement在HTMLDOM中出现的次数?,java,list,selenium,selenium-webdriver,webdriver,Java,List,Selenium,Selenium Webdriver,Webdriver,我有一个返回WebElement的函数。现在我需要找出它的发生或者说它出现的时间 例如 我有另一个方法,它将参数作为字符串: public int elementCount(String string) { int i = driver.findElements(By.xpath(string)).size(); if (i > 0) { System.out.println("Element count is "+i); } else {

我有一个返回
WebElement
的函数。现在我需要找出它的发生或者说它出现的时间

例如

我有另一个方法,它将参数作为字符串:

public int elementCount(String string) {
    int i = driver.findElements(By.xpath(string)).size();
    if (i > 0) {
        System.out.println("Element count is "+i);
    } else {
        System.out.println("Element not found);
    }
    return i;
}
我需要另一个方法,它将
WebElement
作为参数,并给出计数。我试图用
By
将其转换为
org.openqa.selenium.remote.RemoteWebElement,但它给了我错误
org.openqa.selenium.RemoteWebElement无法转换为org.openqa.selenium.By
想不出其他任何东西

我使用的是Windows、Java、Selenium、testNg、Maven

List ele=driver.findElements(按.tagName(“a”);
List <WebElement> ele=driver.findElements(By.tagName("a")); 
System.out.println(ele.size());
System.out.println(ele.size());
driver.findElements(By.xpath(string))将返回WebElements列表

然后,您可以定义类似的方法:

public int getCount(List<WebElement> ele){
    if(ele!=null)return ele.size();
    return 0; // or can throw the exception
}
public int getCount(列表元素){
如果(ele!=null)返回ele.size();
返回0;//或者可以引发异常
}
WebElement 表示中的单个HTML元素。因此,每个WebElement都是唯一的,并且它的存在不能出现在世界上的多个地方

要查找WebElement,需要按如下方式调用该方法:

driver.findElement(By.xpath("unique_xpath_of_webelement"));
driver.navigate().to("https://www.msn.com");
List<WebElement> elementList = driver.findElements(By.tagName("a"));
if (elementList.size()>0){
    foo();
} else {
    bar();
}
但根据您的代码试用,如果您想查找任何特定标记的编号,例如
方法,如下所示:

driver.findElement(By.xpath("unique_xpath_of_webelement"));
driver.navigate().to("https://www.msn.com");
List<WebElement> elementList = driver.findElements(By.tagName("a"));
if (elementList.size()>0){
    foo();
} else {
    bar();
}
现在,您可以随时从
main()
/
@Test
调用该方法以及所需的
xpath
,如下所示:

int myCount = elementCount("//*[contains(text(),'paul')]")

无法从现有元素中提取定位器

在您的示例中,您传递了一个表示定位器的
字符串
,并获得已找到元素的计数。我建议您稍微更改一下,改为使用

如果使用
字符串
,则该方法将绑定到特定的定位器类型,即XPath。如果您通过
定位器获取一个
,则可以有一个单一的方法来获取任何定位器类型

我建议你把方法改为

public int elementCount(By locator) {
    return driver.findElements(locator).size();
}
如果您只想测试元素的存在性(例如,在您的测试用例中,count>0),那么您可以将上述函数更改为

public bool elementExists(By locator) {
    return driver.findElements(locator).size() > 0;
}
使用此选项会将您的测试用例更改为

@Test
public void elementCount() {
    navigate("https://www.msn.com");
    elementExists(By.tagName("a")) ? foo() : bar();
}