Java爬取百度指数

由于在实际的应用中,也可能会使用到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的定时任务),所以能够定时执行爬取数据的任务哦。

本文只为记录我在实际中遇到的问题和解决的方法,代码写的较为臃肿,如有不足还请见谅,若有更好的解决方式,可以评论出来大家一起参考。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用Java中的Jsoup库来实现百度百科网页信息并保存到本地。下面是一个简单的示例代码,可以帮助你快速入门: ``` import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class Main { public static void main(String[] args) { String url = "https://baike.baidu.com/item/Java/85979"; try { // 使用Jsoup连接到指定的URL,并获HTML文档 Document doc = Jsoup.connect(url).get(); // 获百度百科页面的标题 String title = doc.title(); System.out.println("标题: " + title); // 获百度百科页面的所有段落信息 Elements paragraphs = doc.select(".main-content .para"); // 将所有段落信息写入文本文件 BufferedWriter writer = new BufferedWriter(new FileWriter("Java百度百科.txt")); for (Element paragraph : paragraphs) { writer.write(paragraph.text()); writer.newLine(); } writer.close(); System.out.println("并保存成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在这个示例中,我们首先使用Jsoup库连接到指定的URL(这里是Java百度百科页面),并获HTML文档对象。然后,我们使用CSS选择器从文档对象中获所有段落信息,并将这些信息写入本地文本文件中。 需要注意的是,这个示例仅供参考,实际应用中需要处理更多的异常情况和错误处理。此外,网页信息需要遵守相关法律法规,不得用于非法用途。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值