我想在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());
}
}
}
答案 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来获取它们。