如何在自动登录后将Cookie导出到Selenium中的文件

时间:2016-04-14 18:57:52

标签: 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 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());
        }

    }
}

1 个答案:

答案 0 :(得分:1)

这是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来获取它们。