java抓取网页指定元素/内容

来源:互联网 发布:在淘宝上怎么注册账号 编辑:程序博客网 时间:2024/06/05 20:57

一、利用jsoup抓取网页,并获得指定dom元素

jsoup jar  下载地址 https://jsoup.org/download

try {Document doc = null;doc = Jsoup.connect("http://www.163.com/xxx.html").get();// dom解析获得指定元素Element mainArea = doc.getElementById("mainArea");Elements datas = mainArea.getElementsByAttribute("data-period");// 遍历Elements datas,获取指定属性for(Element data:datas){String win_number = data.attr("data-win-number");String period = data.attr("data-period");}} catch (IOException e) {System.out.println("以上地址未获取到页面");e.printStackTrace();}


二、利用HttpURLConnection获取ajax返回json数据

try {// json请求地址String urlStr = "xxxxxx";// 创建连接URL url = new URL(urlStr);// 请求地址HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestMethod("GET");// 这里是请求方式 ,或者"POST"connection.setUseCaches(false);connection.setInstanceFollowRedirects(false);// content-Type要根据目标接口的类型填,常用就"form"// 百度网站自身防盗链,直接发起get请求没有结果,抓取真实请求参数connection.setRequestProperty("Referer", "http://www.baidu.com/XXXXXXXXXX");connection.connect();// 读取响应BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));String ss = null;String total = "";// 输出响应结果。校验你是否操作成功while ((ss = reader.readLine()) != null) {total += ss;}System.out.println("total=" + total);// 解析响应结果:将json String 转换为JSONObjectJSONObject rootJsonObj = JSONObject.fromObject(total);// 解析JSONObject,如下两种get方式JSONObject data =  rootJsonObj.getJSONObject("data");//同(JSONObject) data.get("data")JSONArray list =  data.getJSONArray("list"); //同(JSONArray) data.get("list")// 断开连接reader.close();connection.disconnect();} catch (Exception e) {e.printStackTrace();}


1 0
原创粉丝点击