由于在实际的应用中,也可能会使用到Java来获取百度指数的数据,结合我的前一篇博客(https://blog.csdn.net/weixin_43933556/article/details/118163875),整体思路大致一样,在SpringBoot的测试类中编写单元测试完成数据的获取。
本次使用HuTool工具的HttpRequest类发起请求,使用org.json.JSONObject和JSONArray类对返回的JSON数据进行解析,由于Java中目前我对JSON数据解析掌握的知识有限,暂时只能一层一层的解析JSON数据,不像Python那样解析很方便。
1.思路
还是和前一篇博客的思路一致,通过构建请求头并发起请求,获取数据并解析,然后对数据进行解密,存进List集合(数组也行),或者直接就打印解密之后的String类型的数据也可以,根据实际需要就好。
2.难点
2.1 必须要登录之后找到请求数据的Cookie,教程请参考我的上一篇博客(https://blog.csdn.net/weixin_43933556/article/details/118163875),这里不再赘述。
2.2 要找到Python的数据类型和对应的Java的数据类型,例如[]对应List,{}对应Map,才能将Python的解密算法转化为Java版本。
2.3 将前一篇博客的Python算法转化为Java代码,需要找到对应的数据类型和属性Java对应的Api,需要对Map和List非常熟悉,代码如下:
/**
* 解密算法
*
* @param key 密钥
* @param data 加密的数据
* @return 解密之后的字符串数据
*/
public String decryption(List<String> key, List<String> data) {
Map<String, String> map = new HashMap<>();
for (int i = 0; i < key.size() / 2; i++) {
map.put(key.get(i), key.get(key.size() / 2 + i));
}
StringBuilder decrypt_data = new StringBuilder();
for (String datum : data) {
decrypt_data.append(map.get(datum));
}
return decrypt_data.toString();
}
3.爬取的步骤
3.1 导入依赖,别导错了,也可以使用原生的HttpClient完成,具体使用什么都行,看自己最熟悉什么即可。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.7</version>
</dependency>
3.2 根据获取数据的url构建请求头,并发起get请求。
String searchUrl = "https://index.baidu.com/api/SearchApi/index?area=0&word=[[{%22name%22:%22丽江古城%22,%22wordType%22:1}]]&days=30";
String searchResult = HttpRequest.get(searchUrl)
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "gzip, deflate, br")
.header("Accept-Language", "zh-CN,zh;q=0.9")
.header("Connection", "keep-alive")
.header("Cookie", "你登陆之后的Cookie")
.header("Host", "index.baidu.com")
.header("Referer", "https://index.baidu.com/v2/main/index.html")
.header("sec-ch-ua", "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36")
.execute().body();
3.3 解析数据
JSONObject jsonObject = new JSONObject(searchResult);//将String类型的数据转换为JSONObject对象
//开始解析搜索指数的json数据
JSONObject dataJson = jsonObject.getJSONObject("data");
//解析出uniqid
String uniqid = dataJson.getString("uniqid");
System.out.println("uniqid:" + uniqid);
//userIndexes下是数组格式的数据,要使用JSONArray来进行解析
JSONArray userIndexesJson = dataJson.getJSONArray("userIndexes");
System.out.println("userIndexes:" + userIndexesJson);
//userIndexes下的数据仍是数组格式,需要通过下标取值
JSONObject userIndexesJson0 = userIndexesJson.getJSONObject(0);//下标为0的数据
System.out.println("userIndexesJson0:" + userIndexesJson0);
JSONObject allJson = userIndexesJson0.getJSONObject("all");
System.out.println("all:" + allJson);
String data = allJson.getString("data");
String endDate = allJson.getString("endDate");
String startDate = allJson.getString("startDate");
System.out.println("原加密数据:" + data);
System.out.println("开始日期:" + startDate);
System.out.println("结束日期:" + endDate);
3.4 获取密钥
//开始获取密钥
String keyUrl = "https://index.baidu.com/Interface/ptbk?uniqid=" + uniqid;
String keyResult = HttpRequest.get(keyUrl)
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "gzip, deflate, br")
.header("Accept-Language", "zh-CN,zh;q=0.9")
.header("Connection", "keep-alive")
.header("Cookie", "你登陆之后的Cookie")
.header("Host", "index.baidu.com")
.header("Referer", "https://index.baidu.com/v2/main/index.html")
.header("sec-ch-ua", "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36")
.execute().body();
JSONObject keyJson = new JSONObject(keyResult);
//解析出密钥
String key = keyJson.getString("data");
System.out.println("密钥:" + key);
3.5 解密,值得注意的是,解密是需要将对应的密钥和加密之后的数据转化为List哦
//将加密的数据和密钥转换为List
String[] dataArr = data.split("");
String[] keyArr = key.split("");
List<String> keyList = new ArrayList<>(key.length());
List<String> dataList = new ArrayList<>(data.length());
keyList.addAll(Arrays.asList(keyArr));
dataList.addAll(Arrays.asList(dataArr));
String decryptionData = decryption(keyList, dataList);
System.out.println("解密之后的String类型数据:" + decryptionData);
//将解密的数据转换为List
String[] decryptionDataArr = decryptionData.split(",");
List<Integer> decryptionList = new ArrayList<>(decryptionDataArr.length);
//处理解密数据中的空值
for (String dec : decryptionDataArr) {
if (isEmpty(dec)) dec = "0";
decryptionList.addAll(Collections.singleton(Integer.parseInt(dec)));
}
System.out.println("解密之后的list数据:" + decryptionList);
4.全部代码
import cn.hutool.http.HttpRequest;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import java.util.*;
public class BaiduIndexTest {
@Test
void testGetBaiduIndexData() throws Exception {
//获取搜索指数的数据
String searchUrl = "https://index.baidu.com/api/SearchApi/index?area=0&word=[[{%22name%22:%22丽江古城%22,%22wordType%22:1}]]&days=30";
String searchResult = HttpRequest.get(searchUrl)
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "gzip, deflate, br")
.header("Accept-Language", "zh-CN,zh;q=0.9")
.header("Connection", "keep-alive")
.header("Cookie", "你登陆之后的Cookie")
.header("Host", "index.baidu.com")
.header("Referer", "https://index.baidu.com/v2/main/index.html")
.header("sec-ch-ua", "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36")
.execute().body();
JSONObject jsonObject = new JSONObject(searchResult);//将String类型的数据转换为JSONObject对象
//开始解析搜索指数的json数据
JSONObject dataJson = jsonObject.getJSONObject("data");
//解析出uniqid
String uniqid = dataJson.getString("uniqid");
System.out.println("uniqid:" + uniqid);
//userIndexes下是数组格式的数据,要使用JSONArray来进行解析
JSONArray userIndexesJson = dataJson.getJSONArray("userIndexes");
System.out.println("userIndexes:" + userIndexesJson);
//userIndexes下的数据仍是数组格式,需要通过下标取值
JSONObject userIndexesJson0 = userIndexesJson.getJSONObject(0);//下标为0的数据
System.out.println("userIndexesJson0:" + userIndexesJson0);
JSONObject allJson = userIndexesJson0.getJSONObject("all");
System.out.println("all:" + allJson);
String data = allJson.getString("data");
String endDate = allJson.getString("endDate");
String startDate = allJson.getString("startDate");
System.out.println("原加密数据:" + data);
System.out.println("开始日期:" + startDate);
System.out.println("结束日期:" + endDate);
//开始获取密钥
String keyUrl = "https://index.baidu.com/Interface/ptbk?uniqid=" + uniqid;
String keyResult = HttpRequest.get(keyUrl)
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "gzip, deflate, br")
.header("Accept-Language", "zh-CN,zh;q=0.9")
.header("Connection", "keep-alive")
.header("Cookie", "你登陆之后的Cookie")
.header("Host", "index.baidu.com")
.header("Referer", "https://index.baidu.com/v2/main/index.html")
.header("sec-ch-ua", "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36")
.execute().body();
JSONObject keyJson = new JSONObject(keyResult);
//解析出密钥
String key = keyJson.getString("data");
System.out.println("密钥:" + key);
//将加密的数据和密钥转换为List
String[] dataArr = data.split("");
String[] keyArr = key.split("");
List<String> keyList = new ArrayList<>(key.length());
List<String> dataList = new ArrayList<>(data.length());
keyList.addAll(Arrays.asList(keyArr));
dataList.addAll(Arrays.asList(dataArr));
String decryptionData = decryption(keyList, dataList);
System.out.println("解密之后的String类型数据:" + decryptionData);
//将解密的数据转换为List
String[] decryptionDataArr = decryptionData.split(",");
List<Integer> decryptionList = new ArrayList<>(decryptionDataArr.length);
//处理解密数据中的空值
for (String dec : decryptionDataArr) {
if (isEmpty(dec)) dec = "0";
decryptionList.addAll(Collections.singleton(Integer.parseInt(dec)));
}
System.out.println("解密之后的list数据:" + decryptionList);
}
/**
* 解密算法
*
* @param key 密钥
* @param data 加密的数据
* @return 解密之后的字符串数据
*/
public String decryption(List<String> key, List<String> data) {
Map<String, String> map = new HashMap<>();
for (int i = 0; i < key.size() / 2; i++) {
map.put(key.get(i), key.get(key.size() / 2 + i));
}
StringBuilder decrypt_data = new StringBuilder();
for (String datum : data) {
decrypt_data.append(map.get(datum));
}
return decrypt_data.toString();
}
/**
* 判断是否为空
*
* @param string 需要判断的参数
* @return 判断的结果
*/
public boolean isEmpty(String string) {
return string == null || "".equals(string);
}
}
5.总结
本次使用Java获取百度指数中的搜索指数,除了需要手动将登录之后的Cookie保存下来,能够自动获取数据并解析,因为在实际开发的过程中,不一定要用Python来进行爬取数据,Java也是可以爬取数据的,而且Java中,本人对定时任务掌握比Python要好(PS:其实就是不会Python的定时任务),所以能够定时执行爬取数据的任务哦。
本文只为记录我在实际中遇到的问题和解决的方法,代码写的较为臃肿,如有不足还请见谅,若有更好的解决方式,可以评论出来大家一起参考。