提问人:Sheriff Sulemana 提问时间:8/5/2023 最后编辑:undetected SeleniumSheriff Sulemana 更新时间:8/6/2023 访问量:92
如何使用 Selenium 关闭 cookie 横幅
How to close the cookie banner using Selenium
问:
此页面上有一个 cookie,我尝试使用 selenium java 和 testNG 关闭它,但没有关闭。网址 https://hausrat.allianz.de/
以下是我的代码:
public void closeCookieNotification() {//*[@id="onetrust-accept-btn-handler"]
try {
// Check if the cookie notification element is present
WebElement cookieNotification = driver.findElement(By.xpath("//*[@id=\"onetrust-accept-btn-handler\"]"));
// Close the cookie notification if present
if (cookieNotification.isDisplayed()) {
WebElement closeButton = driver.findElement(By.xpath("//*[@id=\"onetrust-accept-btn-handler\"]"));
closeButton.click();
}
} catch (Exception e) {
// Cookie notification not present or error occurred while closing, ignore
System.out.println(e.getMessage());
}
}
答:
1赞
Yaroslavm
8/5/2023
#1
在这种情况下,您应该使用,直到出现同意模式。 立即执行,并且不会在站点加载后直接显示同意。WebDriverWait
findElement
您可以尝试以下代码:
WebDriverWait wdwait = new WebDriverWait(driver, 10);
driver.get("https://www.allianz.de/recht-und-eigentum/hausratversicherung/");
WebElement consent = wdwait.until(ExpectedConditions.visibilityOfElementLocated(By.id("onetrust-accept-btn-handler")));
consent.click();
wdwait.until(ExpectedConditions.invisibilityOf(consent));
1赞
undetected Selenium
8/6/2023
#2
该元素是一个动态元素,因此要单击可单击的元素,您需要为 elementToBeClickable() 诱导 WebDriverWait,并且可以使用以下任一定位器策略:
使用 id:
driver.get("https://hausrat.allianz.de/"); new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.id("onetrust-accept-btn-handler"))).click();
使用 cssSelector:
driver.get("https://hausrat.allianz.de/"); new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button#onetrust-accept-btn-handler"))).click();
使用 xpath:
driver.get("https://hausrat.allianz.de/"); new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@id='onetrust-accept-btn-handler']"))).click();
评论