java - 有没有使用 selenium webdriver 绕过 cookie iframe 的解决方案?
问题描述
我在以下嵌入 iframe 的网站上接受 cookie 警报时遇到问题:
我尝试了很多方法来解决使用driver.switchTo().frame()
- 方法的问题:
- 通过使用 iframe 的 ID
sp_message_iframe_234327
- 通过为 iframe 插入索引
0
- 通过 WebElement 调用 iframe
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);
不幸的是,他们都没有工作。我总是遇到以下异常:
org.openqa.selenium.NoSuchFrameException
有没有人知道这个具体的例子可以正确打开 iframe?我在 Java 上使用 Selenium WebDriver 3.141.59,我的测试应该在 Mozilla Firefox (80.0.1) 和 Chromium (85.0.4183.102) 上执行。这两个浏览器是无头启动的。很高兴有任何帮助。
解决方案
Alle akzeptieren要在 url https://www.hamburg.de/中单击,因为所需的元素在 a 内,<iframe>
所以您必须:
为所需的frameToBeAvailableAndSwitchToIt诱导WebDriverWait。
为所需的elementToBeClickable诱导WebDriverWait。
您可以使用以下任一定位器策略:
使用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();
浏览器快照:
参考
您可以在以下位置找到一些相关的讨论: