爬虫_爬取有道每日一句

//emmmm爬虫使我快乐/捂脸

 

emmmm想在自己的网站上弄个每日一句,就写了个爬虫,写了一个半小时吧,网易还是有、东西的

大致流程如下:

先找到有道的官网网页-->点进去,F12-->刷新,查看network-->从上至下排查,找出可疑的包-->分析包-->编写程序-->json解析-->获取成功

 

下面直接上源码(java):

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class youdao_one {
    public static void main(String[] args) {
        StringBuilder json_content = new StringBuilder();
        String api_head = "http://dict.youdao.com/infoline/web?mode=publish&client=web&keyfrom=dict2.index&startDate=";
        String api_tail = "&callback=vistaCallback";
        String date_format = "";
        try {
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd") ;
            date_format = dateFormat.format(date);
            String date_str = api_head + date_format + api_tail;
            URL url = new URL(date_str);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line ;
            while((line = bf.readLine())!=null){
                json_content.append(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String result = json_content.subSequence(json_content.indexOf("(")+1,json_content.indexOf(")")).toString();
//        System.out.println(result);
        JSONObject json = JSONObject.fromObject(result);
        JSONArray json_array = json.getJSONArray(date_format);
        int amount = json_array.size();
        int index = -1;
        for(int i = 0;i<amount;i++) {
            String type = json_array.getJSONObject(i).get("type").toString();
            if(type.equals("壹句")){
                index = i;//保存位置
                break;
            }
//            System.out.println(type);
        }
        System.out.println(json_array.getJSONObject(index).get("summary"));
        System.out.println(json_array.getJSONObject(index).get("title"));
        System.out.println(json_array.getJSONObject(index).get("time"));
        System.out.println(json_array.getJSONObject(index).get("source"));
    }
}

 

希望对大家有所帮助

以上

 

posted @ 2019-06-05 15:49  醉生梦死_0423  阅读(644)  评论(0编辑  收藏  举报