Jsoup後臺解析html、jsp網頁
阿新 • • 發佈:2018-12-25
在一些網路爬蟲或者從第三方網站抓取資訊的程式都面臨1個問題,如何從網頁中把所需的資訊提取出來,Jsoup是個比較好的選擇,它能把網站內容解析成Document,再從document中取element就是個簡單的事了。這裡介紹1下Jsoup的基本用法。
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);
}