jsoup解析html页面

欢迎关注朋友的公众号“证件照一键换底色”,可处理证件照(换背景、换底色、换正装)

引用jar包:

   jsoup-1.10.3.jar

发起POST请求,获取需要页面的java代码:

	/**
	 * 发起post请求,获取需要的html文档
	 * @return
	 * @throws Exception
	 */
	public static String getHTML() throws Exception{
		// 1.构建post所提交的数据
		Map<String, String> postData = new HashMap<String, String>();
		postData.put("key1","value1"); // 根据实际情况添加这里的数据
		// 2.建立链接
		Connection connection = Jsoup.connect("http://www.test.com");// 根据实际情况填写url
		// 3.发起请求
		Response response = connection.method(Method.POST).data(postData).execute();
		// 4.打印执行结果
		System.out.println(response.body());
		return response.body();
	}

需要被解析的html文档片段

<table width="100%" class="dataList">
	<tr>
		<th>手机号码</th><th>返回内容</th>
	</tr>
	<tr>
		<td>133888888888</td>
		<td>开通成功</td>
	</tr>
	<tr>
		<td>13366666666</td>
		<td>开通失败</td>
	</tr>
</table>

解析的java代码

private List<HashMap<String, String>> resolveData(String response){
		List<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
		HashMap<String, String> hashMap = null;
		// 1.先解析成document对象
		Document doucuDocument = Jsoup.parse(response);
		// 2.利用select获取表单
		Element table = doucuDocument.select("dataList").first();
		// 3.获取表单中的<tr>标签
		Elements trs = table.getElementsByTag("tr");
		for (Element tr:trs) {
			// 4.获取tr下的td
			Elements tds = tr.getElementsByTag("td");
			if (tds.size() != 0) { // 剔除只包含有th的tr标签
				hashMap = new HashMap<String, String>();
				hashMap.put("phone",tds.get(0).text());
				hashMap.put("content",tds.get(1).text());
				list.add(hashMap);
			}
		}
		return list;
	}

 

代码存于:

https://github.com/zhouhuakang/jsoup_test

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值