问题描述
我在以下嵌入iframe的网站上接受Cookie警报时遇到问题:
我尝试了多种方法来使用driver.switchTo().frame()
-方法来解决该问题:
- 使用iframe
sp_message_iframe_234327
的ID - 通过为iframe
0
插入索引 - 通过WebElement
WebElement element = driver.findElement(By.xpath("//body/div[6]/iframe[@src='https://cdn.privacy-mgmt.com/index.html?message_id=234327&consentUUID=b2cb90ea-dfdd-4655-b6b9-89117ff34893&requestUUID=ccb96546-c6b5-44e7-9869-438b32f7ad89&preload_message=true']")); driver.switchTo().frame(element);
调用iframe
不幸的是,它们都不起作用。我总是遇到以下异常:
org.openqa.selenium.NoSuchFrameException
有人对这个特定示例有一个想法,可以正确打开iframe吗? 我正在使用Java上的Selenium WebDriver 3.141.59,并且我的测试应在Mozilla Firefox(80.0.1)和Chromium(85.0.4183.102)上执行。那两个浏览器被无端启动。 很高兴获得任何帮助。
解决方法
要在网址https://www.hamburg.de/中单击 Alle akzeptieren ,因为所需元素位于<iframe>
中,因此您必须:
-
为所需的 frameToBeAvailableAndSwitchToIt 诱导 WebDriverWait 。
-
为所需的 elementToBeClickable 诱导 WebDriverWait 。
-
您可以使用以下任一Locator Strategies:
-
使用 cssSelector :
driver.get("https://www.hamburg.de/"); new WebDriverWait(driver,10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[id^='sp_message_iframe']"))); new WebDriverWait(driver,10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[aria-label='Alle akzeptieren']"))).click();
-
使用 xpath :
driver.get("https://www.hamburg.de/"); new WebDriverWait(driver,10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(@id,'sp_message_iframe')]"))); new WebDriverWait(driver,10).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='Alle akzeptieren']"))).click();
-
-
浏览器快照:
参考
您可以在以下位置找到一些相关的讨论