众所周知,B站是通过cookie来识别账号的,其中最重要的分三部分
SESSDATA
bili_jct
DedeUserID
然而当我们打开B站控制台查看B站相关参数的时候会发现,除了最重要的这三个,还有更多参数
接下来我们探讨一下如何通过以上三个参数获取到所有的参数并输出
首先代码中引入 selenium
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
然后从官网下载与自己谷歌浏览器版本匹配的chromedriver驱动
以下两个地址都可
链接一: http://chromedriver.storage.googleapis.com/index.html
链接二: https://registry.npmmirror.com/binary.html?path=chromedriver/
找到跟自己谷歌浏览器最相近的版本即可
下载好之后解压chromedriver.exe到谷歌浏览器安装目录 默认安装一般在C:\Program Files\Google\Chrome\Application
基本思路就是通过浏览器用以上三个重要参数登录B站,刷新之后浏览器会自动补齐其他参数,再把补齐的其他参数抓取出来
/**
* 补全cookie
*/
public static String completionCookie(String cookie) {
String driver1 = "webdriver.chrome.driver";
String chromeDriver = "C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe";
System.setProperty(driver1, chromeDriver);
//获取控制 打开浏览器
ChromeOptions chromeOptions = new ChromeOptions();
// 设置后台静默模式启动浏览器
chromeOptions.addArguments("--headless");
WebDriver driver = new ChromeDriver(chromeOptions);
((JavascriptExecutor) driver).executeScript("Object.defineProperties(navigator,{ webdriver:{ get: () => false } })");
//超时等待30秒
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//跳转到网页
driver.get("https://www.bilibili.com/");
JSONObject cookieJson = getCookieJsonByCookie(cookie);
//模拟登陆,手动设置cookie
String sessdata = cookieJson.getString("SESSDATA");
Cookie excelCookie = new Cookie("SESSDATA", sessdata, ".bilibili.com", "/", null);
driver.manage().addCookie(excelCookie);
String bili_jct = cookieJson.getString("bili_jct");
excelCookie = new Cookie("bili_jct", bili_jct, ".bilibili.com", "/", null);
driver.manage().addCookie(excelCookie);
String dedeUserID = cookieJson.getString("DedeUserID");
excelCookie = new Cookie("DedeUserID", dedeUserID, ".bilibili.com", "/", null);
driver.manage().addCookie(excelCookie);
//刷新页面
driver.get("https://www.bilibili.com/");
//获取ck
Set<Cookie> cookies = driver.manage().getCookies();
Object[] objects = cookies.toArray();
String res2 = "";
for (Object object : objects) {
Cookie cookie1 = (Cookie) object;
String value = cookie1.getValue();
String name = cookie1.getName();
res2 += name + "=" + value + ";";
}
driver.close();
return res2.substring(0, res2.length() - 1);
}
/**
* 从cookie中拆出来参数
*/
private static JSONObject getCookieJsonByCookie(String cookie) {
JSONObject json = new JSONObject();
String[] pairs = cookie.split(";");
for (String pair : pairs) {
String[] keyValue = pair.split("=");
if (keyValue.length == 2) {
String key = keyValue[0].trim();
String value = keyValue[1].trim();
json.put(key, value);
}
}
return json;
}