gpt4 book ai didi

java - Selenium WebDriver 即使切换到 iframe 也无法找到它

转载 作者:行者123 更新时间:2023-12-01 12:49:40 24 4
gpt4 key购买 nike

我搜索了很多论坛主题来解决我的问题,但没有发现任何类似的问题。我正在使用 Java 使用 Selenium WebDriver 编写测试。

我正在测试的网站使用 iframe,用户的所有可见内容都将加载到其中。它看起来像这样:

<html>
<head>
(...)
</head>
<body>
<iframe id="portalIframe">
<html>
<body>
<h2 id="aui_3_2_0_1594">Etat des agents</h2>
...
</body>
</html>
</iframe>
</body>
</html>

我的问题如下:在 iframe 中查找元素并不总是有效。当我想要定位这样的元素时,我首先运行一个方法来切换到 iframe :

protected void switchIframe() {
WebDriverWait wait = new WebDriverWait(driver, 10);
By by = By.id("portalIframe");
try {
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(by));
} catch (TimeoutException e) {
e.printStackTrace();
}
}

然后我可以找到一个 h2 元素:

 driver.findElement(By.xpath("//h2[contains(text(),'Some text')]"));

我无法理解的是,有时 Selenium 无法在网页上找到元素。例如,我刚刚设法找到 h2 元素,然后单击菜单链接加载另一个页面,但是当我尝试在新页面上再次查找 < h2 > 元素时,我收到“未找到元素错误”,如果我尝试在此之前添加 switchIframe(),selenium 说它找不到 iframe。

这似乎是“随机”发生的,所以我真的不知道该如何解决这个问题。ChromeDriver 和 FirefoxDriver 上的问题相同。我不使用其他驱动程序,因为这个私有(private)网站将仅使用 Firefox 和 Chrome。

编辑很抱歉我无法粘贴 html 内容,因为这是一个内联网网站,我无法在这里分享。我尝试定位的 h2 元素的示例 < h2 id="aui_3_2_0_1594">代理国家

而且我的问题与这个问题非常相似: Selenium WebDriver not able to find elements which are not present in the Page Source but present in HTML when seen through Developer Tools该问题不仅出现在 h2 元素上,而且还出现在我想单击的“a”元素上。

谢谢

最佳答案

看来我在寻找 html 元素时没有等待足够的时间。我只是增加了显式等待方法的超时时间。我不是在谈论 switchIframe(),而是指另一种用于等待元素出现的方法:

因此,我将超时时间从 3 秒增加到 6 秒,现在看起来效果很好。

protected WebElement waitForElementVisible(By by) {
WebDriverWait wait = new WebDriverWait(driver,6);
WebElement element = null;

try {
element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));
} catch (TimeoutException e) {
//method logging an error
error("Timeout : element " + by.toString() + " is not visible");
}
return element;
}

关于java - Selenium WebDriver 即使切换到 iframe 也无法找到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24329728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com