使用Jsoup解析HTML頁面


在寫Android程序時,有時需要解析HTML頁面,特別是那類通過爬網站抓取數據的應用,比如:天氣預報等應用。如果是桌面應用可以使用 htmlparser這個強大的工具,但是在Android平台上使用會出現錯誤;另一種辦法是使用正則表達式來抽取數據;再有一個辦法是純字符串查找定位來實現。文本將要介紹的是使用 Jsoup這個開源的解析器來實現。
Jsoup既可以通過一個url網址,也可以通過存儲html腳本的文件或者是存儲html腳本的字符串作為數據源,然后通過DOM、CSS選擇器來查找、抽取數據。
示例:
//url網址作為輸入源
Document doc = Jsoup.connect("http://www.example.com").timeout(60000).get();
//File文件作為輸入源
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://www.example.com/");
//String作為輸入源
Document doc = Jsoup.parse(htmlStr);
和java script類似,Jsoup提供了下列的函數
getElementById(String id) 通過id獲得元素
getElementsByTag(String tag) 通過標簽獲得元素
getElementsByClass(String className) 通過class獲得元素
getElementsByAttribute(String key)  通過屬性獲得元素

同時還提供下面的方法提供獲取兄弟節點:
siblingElements(), firstElementSibling(), lastElementSibling();nextElementSibling(), previousElementSibling()

用下面方法獲得元素的數據: 
attr(String key)  獲得元素的數據
attr(String key, String value) 設置元素數據
attributes() 獲得所有屬性
id(), className()  classNames() 得到id class的值
text()得到文本值
text(String value) 設置文本值
html() 獲取html 
html(String value)設置html
outerHtml() 獲得內部html
data()獲得數據內容
tag()  得到tag 和 tagName() 得到tagname

操作html提供了下面方法:
append(String html), prepend(String html)
appendText(String text), prependText(String text)
appendElement(String tagName), prependElement(String tagName)
html(String value)
下面舉個列子,通過Jsoup抽取出一個DIV塊里的所有鏈接地址。html文本如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>測試</title>
</head>
<body>
測試連接
<div class="my div">
<a href="page1.html">鏈接地址一</a><br>
<a href="http://www.example.com/page2.html">鏈接地址二</a><br>
</div>
</body>
</html>
Android java代碼如下:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
Document doc = Jsoup.connect("http://www.example.com").timeout(60000).get();
Elements divs = doc.select("div.my div");
StringBuilder linkBuffer = new StringBuilder();
if (divs != null) {
    for (Element div : divs) {
        Elements links = div.select("a[href]");
        if (null != links) {
            for (Element link : links) {
                linkBuffer.append(link.attr("abs:href"));//相對地址會自動轉成絕對url地址
                linkBuffer.append(" ");
                linkBuffer.append(link.text());
            }                                    
        }                                
    }
}
對於Jsoup更詳細的信息,可以看官網的文檔。http://www.open-open.com/jsoup
以上代碼在Android 1.6及以上版本的手機上測試通過。
注意事項:
如果手機是通過wap方式聯網,有可能需要設置http proxy,設置方式如下(代碼放置在Jsoup.connect調用之前):
String host = android.net.Proxy.getDefaultHost();
int port = android.net.Proxy.getDefaultPort();
if (host != null && port != -1) {
    System.getProperties().setProperty("proxySet", "true");
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyPort", Integer.toString(port));
}

本文出自 “技術人生” 博客,請務必保留此出處http://zhaohaiyang.blog.51cto.com/2056753/735346


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM