使用 PhantomJS 无头浏览器切换 iframe 时数组索引越界异常 -1

Array Index out of bounds exception -1 when switching iframes using PhantomJS headless browser

我正在使用 Selenide 编写浏览器测试。在此测试中,我必须多次切换到不同的 iframe。当我 运行 这个测试用 Chrome 时,它工作得很好。但是当我使用 phantomjs 时,有时它可以工作,有时它会失败。我没有看到它失败的原因。

这是我收到的错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
   at java.util.ArrayList.elementData(Unknown Source)
   at java.util.ArrayList.get(Unknown Source)
   at com.codeborne.selenide.impl.CollectionElement.getWebElement(CollectionElement.java:29)
   at com.codeborne.selenide.impl.SelenideElementProxy.dispatchAndRetry(SelenideElementProxy.java:82)
   at com.codeborne.selenide.impl.SelenideElementProxy.invoke(SelenideElementProxy.java:56)
   at com.sun.proxy.$Proxy1.getAttribute(Unknown Source)
   at automationFramework.PegaRulesetCheck.main(PegaRulesetCheck.java:8)

java 代码很长所以我只展示它失败的部分。

79. /*Get the list of iframes*/
80. List<SelenideElement> myIframes = $$("iframe");
81. System.out.println("Switching to iframe " + myIframes.get(myIframes.size() - 1).getAttribute("name"));

所以出于某种原因,有时会失败,有时会成功。很随意。我怀疑创建 iframe 列表的第 80 行并不总是有效。可能是列表是在动态创建其他 iframe 之前创建的,因此无法切换到其他 iframe。但我不知道如何解决这个问题。

好的,所以我能够解决这个问题。我的怀疑是正确的,有时列表是在动态加载所有 iframe 之前创建的。

所以我能够通过使用 for 循环来检查数组是否包含 iframe 来解决这个问题。如果它不包含 iframe,它将等待 100 毫秒。

/*Get the list of iframes*/
List<SelenideElement> myIframes = $$("iframe");

/* For loop that makes sure that the list of iframes is bigger than 0 */
for (int i=1; myIframes.size() < 1; i++){
    Thread.sleep(100);
    myIframes = $$("iframe");
    /* if the script waits for 10 seconds, break out of the for loop. */
    if(i > 99){
        System.out.println("Breaking out of for loop, list of iFrames contains : " + myIframes.size() + " frame.");
        break;
    }
}