当前位置: 动力学知识库 > 问答 > 编程问答 >

Using Iterator with Java Selenium WebDriver

问题描述:

Using Selenium to gather text of all p elements within a specific div. I noticed while using List, Selenium scanned the whole DOM and stored empty text. So, I wanted to iterate through the DOM and only store values that are not equal to empty text via java.util.Iterator. Is this possible? Is there a more efficient way other than the List approach?

Iterator Approach:

public static boolean FeatureFunctionsCheck(String Feature){

try

{

Iterator<WebElement> all = (Iterator<WebElement>) Driver.Instance.findElement(By.xpath("//a[contains(text()," + Feature + ")]/ancestor::h3/following-sibling::div/div[@class='navMenu']/p"));

boolean check = false;

while(all.hasNext() && check){

WebElement temp = all.next();

if(!temp.getText().equals(""))

{

Log.Info("Functions: " + temp.getText());

all = (Iterator<WebElement>) Driver.Instance.findElement(By.xpath("//a[contains(text()," + Feature + ")]/ancestor::h3/following-sibling::div/div[@class='navMenu']/p"));

}

else

check = true;

}

return false;

}

catch(Exception e)

{

Log.Error("Failed()" + e);

return false;

}

}

Iterator Approach throws exception...

java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to java.util.Iterator

List Approach Works, However Not Sure If This Is Efficient

public static boolean FeatureFunctionsCheck(String Feature){

try

{

List<WebElement> AllModelFunctions = new ArrayList<WebElement>();

Log.Info("[Test-235]: Selecting Feature");

for(WebElement element: AllModelFunctions){

if(!element.getText().equals(""))

{

Log.Info("Functions: " + element.getText());

}

}

return false;

}

catch(Exception e)

{

Log.Error("Failed()" + e);

return false;

}

}

网友答案:

findElement returns one WebElement. What you probably meant to do is to search for all elements with given xpath, using findElements:

Driver.Instance.findElements(...

Also the syntax is over-complicated. You can just get the list and iterate through it:

List<WebElement> elements = Driver.Instance.findElements(...);
for(WebElement element : elements) {
    if(!element.getText().equals(""))
    {   
        Log.Info("Functions: " + element.getText());
    }
}

BTW I have to fully trust that Driver.Instance is an instance of the driver (typically in Java you don't have capitals for class instances, so I'm not sure if I understood it right). A more common syntax would be something like:

WebDriver driver = new FirefoxDriver(); // or another browser
driver.findElements(...);
// ...
分享给朋友:
您可能感兴趣的文章:
随机阅读: