代码之家  ›  专栏  ›  技术社区  ›  to_the_nth

在selenium中从文件设置cookie

  •  0
  • to_the_nth  · 技术社区  · 7 年前

    我有:一个持久的文本cookie文件 我想:为selenium请求设置cookie

    代码:

    // go on the domain so we can set the cookie
    driver.get("https://www.thedomain.com/404");
    try {Thread.sleep(2000);} catch (Exception e) {}
    
        try{
           File file = new File('CookieFile.txt');
           FileReader fileReader = new FileReader(file);
           BufferedReader Buffreader = new BufferedReader(fileReader);
           String strline;
           while((strline=Buffreader.readLine())!=null){
                StringTokenizer token = new StringTokenizer(strline,";");
                while(token.hasMoreTokens()){
                     String name = token.nextToken();
                     String value = token.nextToken();
                     String domain = token.nextToken();
                     String path = token.nextToken();
                     Date expiry = null;
    
                     String val;
                     if(!(val=token.nextToken()).equals("null"))
                      {
                         expiry = new Date(val);
                      }
            Boolean isSecure = new Boolean(token.nextToken()).
                                booleanValue();
            Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);
            System.out.println(ck);
            driver.manage().addCookie(ck); // This will add the stored cookie to your current session
                  }
              }
          }catch(Exception ex){
                ex.printStackTrace();
        }
    

    日期字符串:

    2021年2月15日星期一15:38:00

    错误 IDE:

    java.lang.IllegalargumentException

    在Java.UTI.Deal.PalSE(Dea.java:617)

    在Java.UTI.DATE(日期:Java:274)

    在MyCordNe.TestSaveCooKee(MyCythNeord.java:196)

    在sun.reflect.nativeMethodAccessorImpl.invoke0(本机方法)

    编写/创建cookie文件工作正常。日期对象集似乎有问题。有什么想法吗?

    0 回复  |  直到 7 年前
        1
  •  0
  •   Jens Dibbern    7 年前

    这个 java.util.Date(String) 因为某种原因和很长一段时间被弃用。您应该检查以下代码段:

        DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
        try {
          String s = df.format(d);
          System.out.println(s);
          d = df.parse(s);
        } catch (ParseException e) { 
          e.printStackTrace();
        }
    

    那应该符合你的档案。我建议编辑cookie文件并使用简单的日期和时间格式,如

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    

    你必须编辑你的文件并使用如下格式 2019-02-16 17:30:44 .

    How to convert a String to a Date using SimpleDateFormat?

    我建议使用这里描述的java.time包 Differences between Java 8 Date Time API (java.time) and Joda-Time .