Java 如何在自动登录后将cookie导出到Selenium中的文件
在Selenium中成功登录后,我想将cookie和头导出到文件中,我可以使用Selenium登录 下面是我使用Selenium登录网站的代码Java 如何在自动登录后将cookie导出到Selenium中的文件,java,selenium,cookies,selenium-webdriver,Java,Selenium,Cookies,Selenium Webdriver,在Selenium中成功登录后,我想将cookie和头导出到文件中,我可以使用Selenium登录 下面是我使用Selenium登录网站的代码 package login; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.logging.LogEntries; import
package login;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.Logs;
public class Login1 {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:/Program Files (x86)/Google/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("url");
driver.manage().window().maximize();
driver.findElement(By.id("username")).sendKeys("namehere");
driver.findElement(By.id("password")).sendKeys("passhere");
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.findElement(By.id("submit")).click();
Logs logs = driver.manage().logs();
LogEntries logEntries = logs.get(LogType.DRIVER);
for (LogEntry logEntry : logEntries) {
System.out.println(logEntry.getMessage());
}
}
}
这是一个使用Selenium将所有Cookie保存到文件的示例:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
Path cookiesFile = Paths.get("C:\\Temp\\cookies.txt");
// save the cookies to a file for the current domain
try (PrintWriter file = new PrintWriter(cookiesFile.toFile(), "UTF-8")) {
for (Cookie c : driver.manage().getCookies()) {
file.println(c.toString());
}
}
至于标题,Selenium没有提供获取它们的API。使用driver.manage().getCookies()
,您可以获取cookies。因此,您将能够以您想要的方式将其导出到文件中