Jsoup後臺解析html、jsp網頁

在一些網絡爬蟲或者從第三方網站抓取信息的程序都面臨1個問題,如何從網頁中把所需的信息提取出來,Jsoup是個比較好的選擇,它能把網站內容解析成Document,再從document中取element就是個簡單的事了。這裏介紹1下Jsoup的基本用法。

首先需要下載jar包,jsoup-1.9.2.jar

1、Jsoup解析字符串

public void parseString()
	{
		String html = "<html><head><script type=\"text/javascript\">var date = new Date();alert(date);function sub(u){var token = document.getElementById(\"token\").value;var durl = u + \"token=\" + encodeURIComponent(token);window.open(durl);}</script></head><body><br/><br/>token:<input type=\"text\" name=\"token\" id=\"token\" style=\"width:500\" value=\"uGyUoJ8A6+ETMgIVYAHTpt/l/cY=\"/></input> <br/><br/><input class='butt' type=\"button\" value=\"打開本地\" name=\"sub\" onclick=\"sub('http://localhost:8080/mapbar-fieldwork/setting/setting!index.action?')\" style=\"left:200\"></input><input type=\"button\" value=\"打開44\" name=\"sub\" onclick=\"sub('http://10.30.20.44:8181/mapbar-fieldwork/setting/setting!index.action?')\" style=\"left:200\"></input><input type=\"button\" value=\"獲取權限接口\" name=\"sub\" onclick=\"sub('http://localhost:8080/mapbar-fieldwork/newaccount/newaccount!queryUserPermissions.action?projectId=666&')\" style=\"left:200\"></input><input type=\"button\" value=\"獲取權限接口\" name=\"sub\" onclick=\"sub('http://localhost:8080/mapbar-fieldwork/newaccount/newaccount!queryProjectPermissions.action?projectId=666&')\" style=\"left:200\"></input></body></html>";
		
		//Jsoup解析html
		Document doc =Jsoup.parse(html,"utf-8");
		
		//根據id獲取元素
		Element e1 = doc.getElementById("token");
		
		//根據屬性獲取元素s
		Elements e2s = doc.getElementsByAttribute("onclick");
		
		//根據屬性+屬性值
		Elements e3s = doc.getElementsByAttributeValue("type", "text");
		
		//根據class
		Elements e4s = doc.getElementsByClass("butt");
		
		//根據 標籤
		Elements e5s = doc.getElementsByTag("head");
		
		Elements e6s = doc.select("input[type]");
		
		p(e6s); 
		
	}

2、Jsoup解析url

Jsoup可以直接解析1個網址,把網站的返回內容解析出來

public void parseUrl()
	{
		try 
		{
			URL url = new URL("http://www.baidu.com");
			Document doc = Jsoup.parse(url, 1000);
			Elements e1s = doc.select("a[href=http://news.baidu.com]");
			p(e1s);
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
	}

3、Jsoup解析本地文件

可以把html文件解析出來

public void parseFile()
	{
		File file = new File("C:/Users/Administrator/Desktop/測試頁面.html");
		try {
			Document doc = Jsoup.parse(file, "GBK");
			p(doc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}



public static void p(Object o)
	{
		System.out.println(o);
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章