java抓取网页指定元素/内容
2017-02-24 09:44
288 查看
一、利用jsoup抓取网页,并获得指定dom元素
jsoup jar 下载地址 https://jsoup.org/downloadtry { 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 转换为JSONObject JSONObject 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(); }
相关文章推荐
- java-抓取指定URL网页的内容
- Java 抓取网页内容,获取指定服务器IP
- java-抓取指定URL网页的内容(二)
- Java 抓取网页内容,获取指定服务器IP
- 抓取网页中指定节点的内容(java版本)
- JAVA 抓取网页内容
- 通过java.net.Socket 类抓取网页内容
- JAVA抓取网站网页内容
- 通过java.net.URL类抓取某个网页的内容 选择自 cqq 的 Blog
- node js 抓取指定网页内容gb2312乱码问题解决
- JAVA在线抓取网页中的元素的例子(使用JSoup包进行解析)
- 通过java.net.URL类抓取某个网页的内容
- java抓取网页内容--生成静态页面
- JAVA 抓取网页内容
- 爬网入门:JAVA抓取网站网页内容
- 使用java的html解析器jsoup和jQuery实现一个自动重复抓取任意网站页面指定元素的web应用
- JAVA常用整理(1)--通过java.net.URL类抓取某个网页的内容
- java 抓取网页内容,可设定代理(HttpURLConnection)
- java 抓取网页内容
- 使用java的html解析器jsoup和jQuery实现一个自动重复抓取任意网站页面指定元素的web应用