Selenium - 使用Java记住凭据

时间:2018-03-07 10:16:23

标签: java selenium selenium-webdriver

所以我在下面的Java中使用了这个简单的Selenium脚本(对于Chrome)。

我所要做的就是: 1.登录网站A,记住我的凭据(等于点击浏览器中弹出的“记住我”中的“是”) 2.关掉硒 3.手动打开浏览器并仍然登录

有没有办法做到这一点? 我在stackoverflow上看到了几个类似的问题,但还没有设法使解决方案适用于我的情况。

帮助将不胜感激。

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class MyTestLogin {

public static void main(String[] args) {

    System.setProperty("webdriver.chrome.driver", "C://backup/Automation/drivers/chromedriver.exe");
    WebDriver driver= new ChromeDriver();

    //login to a website A
    driver.get("https://websitea.com");
    driver.findElement(By.name("username")).sendKeys("name.surname");
    driver.findElement(By.name("password")).sendKeys("Huhuhu");
    driver.findElement(By.className("flatbutton")).click();     

    driver.quit();

}

} 

编辑:// Heureka!

经过大量改写后&来自StackOverflow的大量帮助,我终于能够编写一个脚本(并使用一个数组作为告诉他要复制哪些文件的方式),这正是应该做的 - 问题是,它无法正常工作。

当我执行以下操作时:

  1. 手动打开浏览器,清理私人数据,关闭浏览器
  2. 手动打开浏览器,手动登录脚本中的所有页面,关闭浏览器
  3. 备份脚本中提到的文件
  4. 手动打开浏览器,清理私人数据,关闭浏览器
  5. 让脚本运行
  6. 浏览器仍然不记得我。但是,当我手动复制步骤3中支持的文件而不是步骤5时,它正在工作。

    我错过了什么?

                import java.io.File;
                import java.nio.file.Files;
                import java.io.IOException;
                import java.nio.file.StandardCopyOption;
                import java.util.Arrays;
    
                import org.openqa.selenium.By;
                import org.openqa.selenium.WebDriver;
                import org.openqa.selenium.chrome.ChromeDriver;
                import org.openqa.selenium.chrome.ChromeOptions;
    
                public class MyTestLogin {
    
                    public static void main(String[] args) {
                        // TODO Auto-generated method stub
                        System.setProperty("webdriver.chrome.driver", "C://backup/Automation/drivers/chromedriver.exe");
                        ChromeOptions options = new ChromeOptions();
    
                        //Create a new temporary folder to store all the cookies and other website data
                        options.addArguments("user-data-dir=C://Users/user/Desktop/files/cookies");
                        WebDriver driver = new ChromeDriver(options);       
    
                        //login to a website A
                        driver.get("https://websitea.com");
                        driver.findElement(By.name("username")).sendKeys("name.surname");
                        driver.findElement(By.name("password")).sendKeys("password");
                        driver.findElement(By.className("flatbutton")).click();     
                        //new tab
                        //((JavascriptExecutor)driver).executeScript("window.open()");  
    
                        //login to a website B       
                        driver.get("https://websiteb.com");
    
                        driver.findElement(By.id("os_username")).sendKeys("name.surname");
                        driver.findElement(By.id("os_password")).sendKeys("password");
                        driver.findElement(By.id("loginButton")).click();
    
                        /*When you are finished logging in, close the browser
                        otherwise you´re unable to copy current session cookie */
                        driver.quit();
    
                        // now copy all the necessary files from a new folder to a browser´s cookie location        
    
                        //Have a list of files that needs to be copied      
                        java.util.List<String> names = Arrays.asList(
                                "Cookies",
                                "Cookies-journal",
                                "Current Session", 
                                "Current Tabs",         
                                "Favicons",             
                                "Favicons-journal",
                                "History",
                                "History Provider Cache",               
                                "History-journal",
                                "Last Session",
                                "Last Tabs",
                                "Login Data",
                                "Login Data-journal",
                                "Network Action Predictor",
                                "Network Action Predictor-journal",
                                "Network Persistent State",             
                                "Origin Bound Certs",
                                "Origin Bound Certs-journal",
                                "Preferences",
                                "previews_opt_out.db",
                                "QuotaManager",             
                                "QuotaManager-journal",             
                                "Secure Preferences",
                                "Shortcuts",
                                "Shortcuts-journal",
                                "Top Sites",
                                "Top Sites-journal",
                                "Translate Ranker Model",
                                "TransportSecurity",                
                                "Visited Links",
                                "Web Data",
                                "Web Data-journal"              
                                );
    
                        // convert list to array       
                        String[] namesArr = new String[names.size()];
                        namesArr = names.toArray(namesArr);
                        //iterate over array and...     
                        int i=names.size();
                        int s=0;
                        while(i>=1){
    
                             //...for each item on the list, move it from one folder to another         
    
                                System.out.println(namesArr[s]);                
    
                                File sourceFile=new File ("C://Users/user/Desktop/Plocha/cookies/Default/"+namesArr[s]);
                                File destinationFile=new File("C://Users/user/AppData/Local/Google/Chrome/User Data/Default/"+namesArr[s]);
                                    try{ 
                                        Files.copy(sourceFile.toPath(),destinationFile.toPath(),StandardCopyOption.REPLACE_EXISTING);
                                        System.out.println("File copy successfull");                
                                    } catch (IOException e) {
                                        e.printStackTrace();                    
                                    }
                                        s++;                                 
                                        i--;                           
                                    }
    
                        //now delete the temporary folder
                        File directory = new File("C://Users/user/Desktop/Plocha/cookies/");
    
                        //make sure directory exists
                        if(!directory.exists()){
    
                           System.out.println("Directory does not exist.");
                           System.exit(0);
    
                        }else{
    
                           try{
    
                               delete(directory);
    
                           }catch(IOException e){
                               e.printStackTrace();
                               System.exit(0);
                           }
                        }
    
                        System.out.println("Done");
                    }
    
                    public static void delete(File file)
                        throws IOException{
    
                        if(file.isDirectory()){
    
                            //directory is empty, then delete it
                            if(file.list().length==0){
    
                               file.delete();
                               System.out.println("Directory is deleted : "
                                                                 + file.getAbsolutePath());
    
                            }else{
    
                               //list all the directory contents
                               String files[] = file.list();
    
                               for (String temp : files) {
                                  //construct the file structure
                                  File fileDelete = new File(file, temp);
    
                                  //recursive delete
                                 delete(fileDelete);
                               }
    
                               //check the directory again, if empty then delete it
                               if(file.list().length==0){
                                 file.delete();
                                 System.out.println("Directory is deleted : "
                                                                  + file.getAbsolutePath());
                               }
                            }
    
                        }else{
                            //if file, then delete it
                            file.delete();
                            System.out.println("File is deleted : " + file.getAbsolutePath());
                        }
                    }
    
                }
    

1 个答案:

答案 0 :(得分:0)

创建一个空文件夹来存储所有Cookie和其他网站数据。您可以通过设置user-data-dir参数告诉chrome webdriver将其用作文件夹。

ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=/path/to/folder/");
WebDriver driver = new ChromeDriver(options);