[英]How can I accept cookies on a particular site?
在用 Selenium Java 為求職網站編寫基本搜索測試時,我在嘗試接受網站上顯示的 cookie 警告時遇到問題。
該站點有 2 個 cookie 通知,中間層和頂層橫幅相互重疊。
我將不勝感激任何建議(我是 Selenium Java 的新手!),這將使我能夠解決這個有點惱人(但次要)的問題。
這是我使用的代碼無濟於事(兩個 cookie 橫幅都保留在原位):
我嘗試了下面詳述的 xpath 方法
import java.util.Arrays;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Keys;
import java.util.concurrent.TimeUnit;
importnet.bytebuddy.agent.builder.AgentBuilder.RedefinitionStrategy.DiscoveryStrategy.Explicit; //這些是從通過項目級構建路徑>外部庫提供的Selenium包導入的
public class Demo4SeleniumTypeAndClickXPathExperis {
public static void main(String[] args) {
System.setProperty("webdriverchrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.experis.co.uk/");//Browser URL
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//這里是似乎沒有結果的違規項目
driver.findElement(By.xpath("//button[@title='Accept Cookies']")).submit();
driver.findElement(By.xpath("//*[@id=\"query\"]")).sendKeys("test or tester or qa");
driver.findElement(By.xpath("//*[@id=\"search\"]/span/div/div[1]/input")).clear();
driver.findElement(By.xpath("//*[@id=\"search\"]/span/div/div[1]/input")).sendKeys("Bristol");
driver.findElement(By.xpath("//*[@id=\"search\"]/span/div/div[1]/input")).sendKeys(Keys.RETURN);
driver.findElement(By.xpath("//*[@id=\"search\"]/span/div/div[1]/input")).submit();
driver.findElement(By.xpath("//*[@id=\"search\"]/span/div/div[1]/input")).submit();
//driver.close();
}
private static Object navigate() {
// TODO Auto-generated method stub
return null;
我希望能夠接受 cookie 橫幅並從屏幕上清除它們
為了獲得更具體的答案,我建議發布HTML頁面源,其中包括cookie接受按鈕的HTML。
根據我接受Cookie的經驗,您可能不得不將彈出窗口視為警報:
driver.switchTo().alert().accept;
使用以下代碼接受兩個Cookie警報。 我已經在代碼中提供的URL上測試了代碼。
By cookies_accept = By.xpath("//*[@title='Accept Cookies']");
By cookies_gotIt = By.xpath("//a[text()='Got it!']");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(cookies_accept)).click();
wait.until(ExpectedConditions.invisibilityOfElementLocated(cookies_accept));
wait.until(ExpectedConditions.elementToBeClickable(cookies_gotIt)).click();
package com.selenium_abcd;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class cookiesDelete {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver.exe");
WebDriver dr = new ChromeDriver();
dr.manage().deleteAllCookies();
dr.manage().deleteCookieNamed("Cookie name");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.