1、當我們通過發送http請求時,有時候返回結果是一個html格式字符串,你需要從一個網站獲取和解析一個HTML文檔,並查找其中的相關數據。你可以使用下面解決方法:
使用 Jsoup.connect(String url)方法:
//發送請求
Document doc = Jsoup.connect("https://www.baidu.com/").get();
//獲取id號為kw的控件
Element content = doc.getElementById("kw");
//輸出控件所有屬性
System.out.println(content.attributes());
輸出結果
id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off"
頁面源代碼顯示,他其實與輸出結果是一致的,這就好比是selenium自動化框架一樣,通過 driver.findElement(By.id("kw"));找到這個控件,然後堆空間進行各種操作。

connect(String url) 方法創建一個新的 Connection, 和 get() 取得和解析一個HTML文件。如果從該URL獲取HTML時發生錯誤,便會拋出 IOException,應適當處理。
Connection 接口還提供一個方法鏈來解決特殊請求,具體如下:
Document doc = Jsoup.connect("http://example.com")
.data("query", "Java")
.userAgent("Mozilla")
.cookie("auth", "token")
.timeout(3000)
.post();
既然我們想要從html中獲取指定數據,那麼我們先得要找到該控件,我們把它叫做Elements對象,然後才是獲取該控件的某些值。
getElementById(String id) 通過id號查找getElementsByTag(String tag) 標簽名查找getElementsByClass(String className) class名查找getElementsByAttribute(String key) (and related methods)siblingElements(), firstElementSibling(), lastElementSibling();nextElementSibling(), previousElementSibling()parent(), children(), child(int index) attr(String key)獲取屬性attr(String key, String value)設置屬性attributes()獲取所有屬性id(), className() and classNames()text()獲取文本內容text(String value) 設置文本內容html()獲取元素內HTMLhtml(String value)設置元素內的HTML內容outerHtml()獲取元素外HTML內容data()獲取數據內容(例如:script和style標簽)tag() and tagName()append(String html), prepend(String html)appendText(String text), prependText(String text)appendElement(String tagName), prependElement(String tagName)html(String value)1 //發送請求
2 Document doc = Jsoup.connect("https://www.baidu.com/").get();
3 //獲取class名為s_ipt所有element對象
4 Elements element = doc.getElementsByClass("s_ipt");
5 //獲取第一個element對象的name屬性值
6 String value = element.get(0).attr("name");
7 System.out.println(value);
1 //發送請求
2 Document doc = Jsoup.connect("https://www.baidu.com/").get();
3 //獲取id為u1的第一個子元素
4 Element element = doc.getElementById("u1").child(0);
5 //獲取元素鏈接
6 String value1 = element.attr("href");
7 //獲取元素文本內容
8 String value2 = element.text();
輸出結果:
http://news.baidu.com 新聞
1、jsoup學習總結:http://blog.csdn.net/u010814849/article/details/52526582
2、http://www.open-open.com/jsoup/load-document-from-url.htm
3、jsoup學習總結:http://www.cnblogs.com/tomcattd/archive/2013/01/02/2842137.html