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

一、利用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 转换为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)