How to export cookies to a file in Selenium after automated loginAsk Question

问题:

I want to export the cookies along with headers to file after a successful login in Selenium, I am able to login using Selenium.

Below is my code which does login in to a website using 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:


This is an example with Selenium to save all the cookies to a file:

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

As for the headers, well Selenium doesn't provide an API to get them.

标签: selenium cookies selenium-webdriver
© 2014 TuiCode, Inc.