【问题标题】:Element is no longer attached to the DOM selenium webdriver元素不再附加到 DOM selenium webdriver
【发布时间】:2014-10-05 05:00:11
【问题描述】:

我收到一条错误消息。这个错误一般可以,但我无法在我的代码中解决它。有人可以帮我吗?

解释:

我从循环中获取航空公司代码,但是当if(){} 条件开始处理时。我收到一个错误

线程“main” org.openqa.selenium.StaleElementReferenceException 中的异常:元素不再附加到 DOM

这只是所有li 标签之一。 li标签总数为9个。

<li data-airline-id="SU">
    <input id="airline_SU" type="checkbox" checked="checked" title="Aeroflot">
    <label for="airline_SU" class="clearfix">

            <span class="day-filters-label-price">$939</span>

        <span class="day-filters-label-message">Aeroflot</span>
    </label>
</li>

Java 代码:

ul = driver.findElements( By.xpath( "//div[@id='filters-airlines']//ul[@class='clearfix']/li" ) );

    for( WebElement element : ul ){

        String countryCode = element.getAttribute( "data-airline-id" );

        System.out.println( countryCode );

        if( !"DE".equals( countryCode ) ){

            element.findElement( By.id( "airline_" + countryCode ) ).click();

        }

        try{
            Thread.sleep( 1000 );
        }
        catch( InterruptedException e ){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

【问题讨论】:

标签: selenium selenium-webdriver webdriver


【解决方案1】:

您可以使用“黑客”。为避免StaleElementReferenceException,您必须在对其进行某些操作之前重新定位元素。如果我理解你的逻辑,你想取消选中除“DE”之外的所有复选框。您可以使用 XPATH //div[@id='filters-airlines']//ul[@class='clearfix']/li 找到 li's。所以你每次都可以用给定的索引重新定位它

ul = driver.findElements( By.xpath( "//div[@id='filters-airlines']//ul[@class='clearfix']/li" ) );

for( int i = 1; i <= ul.size(); i++ ){

    WebElement li =  driver.findElement( By.xpath( "(//div[@id='filters-airlines']//ul[@class='clearfix']/li)[" + i + "]" ) );

    String countryCode = li.getAttribute( "data-airline-id" );

    System.out.println( countryCode );

    if( !"DE".equals( countryCode ) ){

        li.findElement( By.id( "airline_" + countryCode ) ).click();

    }

    try{
        Thread.sleep( 1000 );
    }
    catch( InterruptedException e ){
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

PS 我不使用 Java,所以语法可能会被破坏一点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-15
    • 2014-06-06
    • 2021-08-05
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多