| 70 | } |
| 71 | |
| 72 | public static void loadCookie(String cookiePath) { |
| 73 | // 首先清除由于浏览器打开已有的cookies |
| 74 | CHROME_DRIVER.manage().deleteAllCookies(); |
| 75 | |
| 76 | // 从文件中读取JSONArray |
| 77 | JSONArray jsonArray = null; |
| 78 | try { |
| 79 | String jsonText = new String(Files.readAllBytes(Paths.get(cookiePath))); |
| 80 | if (!jsonText.isBlank()){ |
| 81 | jsonArray = new JSONArray(jsonText); |
| 82 | } |
| 83 | } catch (IOException e) { |
| 84 | log.error("读取cookie异常!"); |
| 85 | } |
| 86 | // 遍历JSONArray中的每个JSONObject,并从中获取cookie的信息 |
| 87 | if (jsonArray != null) { |
| 88 | for (int i = 0; i < jsonArray.length(); i++) { |
| 89 | JSONObject jsonObject = jsonArray.getJSONObject(i); |
| 90 | String name = jsonObject.getString("name"); |
| 91 | String value = jsonObject.getString("value"); |
| 92 | String domain = jsonObject.getString("domain"); |
| 93 | String path = jsonObject.getString("path"); |
| 94 | Date expiry = null; |
| 95 | if (!jsonObject.isNull("expiry")) { |
| 96 | expiry = new Date(jsonObject.getLong("expiry")); |
| 97 | } |
| 98 | boolean isSecure = jsonObject.getBoolean("isSecure"); |
| 99 | boolean isHttpOnly = jsonObject.getBoolean("isHttpOnly"); |
| 100 | |
| 101 | // 使用这些信息来创建新的Cookie对象,并将它们添加到WebDriver中 |
| 102 | Cookie cookie = new Cookie.Builder(name, value) |
| 103 | .domain(domain) |
| 104 | .path(path) |
| 105 | .expiresOn(expiry) |
| 106 | .isSecure(isSecure) |
| 107 | .isHttpOnly(isHttpOnly) |
| 108 | .build(); |
| 109 | try { |
| 110 | CHROME_DRIVER.manage().addCookie(cookie); |
| 111 | } catch (Exception e) { |
| 112 | log.error("【小问题无须担心】cookie添加异常:【{}】", cookie); |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | public static void getActions() { |
| 119 | ACTIONS = new Actions(Constant.CHROME_DRIVER); |