本人在學習selenium2java中經過瀏覽器插入cookies模擬用戶登陸的時候,發現一個問題,就是token值過時的問題,後來學習了selenium2java鏈接數據庫後找到了一個更好的解決方案。每次插入cookies的時候老是從數據庫拿到最新的token,這樣就完美解決了過時的問題。java
這個是我登陸後從瀏覽器拿到的cookies:sql
[Automatic_login=18436035355%7Ce3ceb5881a0a1fdaad01296d7554868d%7CStudent; expires=星期二, 21 三月 2017 01:59:55 CST; path=/; domain=www.dz101.com, Hm_lvt_52b97b391587eb6d3e582caa097d6f91=1489471192; expires=星期三, 14 三月 2018 01:59:56 CST; path=/; domain=.dz101.com, MyName=18436035355; expires=星期二, 21 三月 2017 01:59:54 CST; path=/; domain=www.dz101.com, User_token_Session=f24f16d472b222271e6dcf27077231b9; expires=星期二, 21 三月 2017 01:59:54 CST; path=/; domain=www.dz101.com, User_identity_Session=1; expires=星期二, 21 三月 2017 01:59:54 CST; path=/; domain=www.dz101.com, PHPSESSID=1s2uvdrj33d72qvj2qlqojhsl7; path=/; domain=www.dz101.com, Hm_lpvt_52b97b391587eb6d3e582caa097d6f91=1489471196; path=/; domain=.dz101.com]數據庫
通過分析和嘗試發現,其實只有插入MyName和User_token_Session這兩項就能夠了。 下面是我成功插入後的cookies:編程
[Hm_lvt_52b97b391587eb6d3e582caa097d6f91=1489472871; expires=星期三, 14 三月 2018 02:27:53 CST; path=/; domain=.dz101.com, MyName=18436035355; path=/; domain=www.dz101.com, User_token_Session=f24f16d472b222271e6dcf27077231b9; path=/; domain=www.dz101.com, PHPSESSID=uahgb7ll1405h0p5jhloipt7a2; path=/; domain=www.dz101.com, Hm_lpvt_52b97b391587eb6d3e582caa097d6f91=1489472873; path=/; domain=.dz101.com]json
下面是我寫的代碼瀏覽器
//向瀏覽器添加cookies public static void addCookies(WebDriver driver, String mobile) throws ClassNotFoundException, SQLException, IOException { Cookie a = new Cookie("MyName", mobile); Cookie b = new Cookie("User_token_Session", MySql.getNewToken(mobile)); driver.manage().addCookie(a); driver.manage().addCookie(b); driver.navigate().refresh(); //查看瀏覽器cookies // Set<Cookie> cooies = driver.manage().getCookies(); // System.out.println(cooies); }
下面是getNewToken(String mobile))方法:cookie
public static String getNewToken(String mobile) throws ClassNotFoundException, SQLException, IOException { // 加載驅動程序 Class.forName(driver); // 鏈接數據庫 Connection conn = DriverManager.getConnection(url, user, password); if (!conn.isClosed()) System.out.println("Succeeded connecting to the Database!"); //statement用來執行SQL語句 Statement statement = conn.createStatement(); // 要執行的SQL語句 String sql = "select * from users where mobile = " + mobile; output(sql); // 結果集 ResultSet rs = statement.executeQuery(sql); System.out.println("查詢結果以下所示:"); String id = null; while (rs.next()) { // 選擇列數據 id = rs.getString("id"); // 輸出結果 System.out.println(rs.getString("id") + "\t" + id); } rs.close(); String sql2 = "select * from users_token where uid = " + id + " ORDER BY create_time DESC LIMIT 1"; ResultSet rs2 = statement.executeQuery(sql2); String token = null; System.out.println("查詢結果以下所示:"); while (rs2.next()) { token = rs2.getString(token); output(token); saveToFile(getNow() + token, "runlog.log", false); } conn.close(); return token; }