天天看點

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

繼續閱讀