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();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yfx000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值