获取网页指定元素和内容

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

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

 
  1. try {

  2. Document doc = null;

  3. doc = Jsoup.connect("http://www.163.com/xxx.html").get();

  4.  
  5. // dom解析获得指定元素

  6. Element mainArea = doc.getElementById("mainArea");

  7. Elements datas = mainArea.getElementsByAttribute("data-period");

  8.  
  9. // 遍历Elements datas,获取指定属性

  10. for(Element data:datas){

  11. String win_number = data.attr("data-win-number");

  12. String period = data.attr("data-period");

  13. }

  14. } catch (IOException e) {

  15. System.out.println("以上地址未获取到页面");

  16. e.printStackTrace();

  17. }


 

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

 
  1. try {

  2. // json请求地址

  3. String urlStr = "xxxxxx";

  4.  
  5. // 创建连接

  6. URL url = new URL(urlStr);// 请求地址

  7. HttpURLConnection connection = (HttpURLConnection) url.openConnection();

  8. connection.setDoOutput(true);

  9. connection.setDoInput(true);

  10. connection.setRequestMethod("GET");// 这里是请求方式 ,或者"POST"

  11. connection.setUseCaches(false);

  12. connection.setInstanceFollowRedirects(false);

  13. // content-Type要根据目标接口的类型填,常用就"form"

  14. // 百度网站自身防盗链,直接发起get请求没有结果,抓取真实请求参数

  15. connection.setRequestProperty("Referer", "http://www.baidu.com/XXXXXXXXXX");

  16. connection.connect();

  17.  
  18. // 读取响应

  19. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

  20. String ss = null;

  21. String total = "";

  22.  
  23. // 输出响应结果。校验你是否操作成功

  24. while ((ss = reader.readLine()) != null) {

  25. total += ss;

  26. }

  27. System.out.println("total=" + total);

  28.  
  29. // 解析响应结果:将json String 转换为JSONObject

  30. JSONObject rootJsonObj = JSONObject.fromObject(total);

  31.  
  32. // 解析JSONObject,如下两种get方式

  33. JSONObject data = rootJsonObj.getJSONObject("data");//同(JSONObject) data.get("data")

  34. JSONArray list = data.getJSONArray("list"); //同(JSONArray) data.get("list")

  35.  
  36. // 断开连接

  37. reader.close();

  38. connection.disconnect();

  39. } catch (Exception e) {

  40. e.printStackTrace();

  41. }

猜你喜欢

转载自blog.csdn.net/jie1521836/article/details/82142015
今日推荐