天天看点

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

继续阅读