【问题标题】:Using Iterator with Java Selenium WebDriver在 Java Selenium WebDriver 中使用迭代器
【发布时间】:2016-05-26 19:59:03
【问题描述】:

使用 Selenium 收集特定 div 中所有 p 元素的文本。我注意到在使用 List 时,Selenium 扫描了整个 DOM 并存储了空文本。所以,我想遍历 DOM,只通过 java.util.Iterator 存储不等于空文本的值。这可能吗?除了 List 方法之外,还有更有效的方法吗?

迭代器方法:

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

迭代器方法抛出异常...

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

列表方法有效,但不确定这是否有效

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

【问题讨论】:

    标签: java selenium iterator listiterator


    【解决方案1】:

    findElement 返回一个 WebElement。您可能打算使用findElements:

    搜索具有给定 xpath 的 all 元素
    Driver.Instance.findElements(...
    

    而且语法过于复杂。您可以获取列表并对其进行迭代:

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

    顺便说一句,我必须完全相信 Driver.Instance 是驱动程序的一个实例(通常在 Java 中,类实例没有大写字母,所以我不确定我是否理解正确)。更常见的语法是这样的:

    WebDriver driver = new FirefoxDriver(); // or another browser
    driver.findElements(...);
    // ...
    

    【讨论】:

    • List 存储所有元素,然后根据条件语句进行记录。但是,我想知道是否可以有条件地将元素存储到 List 以避免存储空字符串。
    • 那么您的实际问题是如何修改.../ancestor::h3/following-sibling::div/div[@class='navMenu']/p 以选择非空文本?
    • 如果你想要的只是非空文本的元素,为什么不使用.../ancestor::h3/following-sibling::div/div[@class='navMenu']/p[text() != '']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    相关资源
    最近更新 更多