一、解析和遍歷一個HTML文檔
1、解析Html及Url鏈接
1 String html = "<html><head><title>First parse</title></head>" 2 + "<body><p>Parsed HTML into a doc.</p></body></html>"; 3 Document doc = Jsoup.parse(html);//解析html文檔
1 Document doc = Jsoup.connect("http://example.com/").get();//解析Url鏈接地址 2 String title = doc.title();
2、解析body片段
1 String html = "<div><p>Lorem ipsum.</p>"; 2 Document doc = Jsoup.parseBodyFragment(html); 3 Element body = doc.body();
parseBodyFragment
方法創建一個空殼的文檔,並插入解析過的HTML到body
元素中。假如你使用正常的 Jsoup.parse(String html)
方法,通常你也可以得到相同的結果,但是明確將用戶輸入作為 body片段處理,以確保用戶所提供的任何糟糕的HTML都將被解析成body元素。Document.body()
方法能夠取得文檔body元素的所有子元素,與 doc.getElementsByTag("body")
相同
3、使用Dom獲取元素
查找元素
4、從元素抽取屬性,文本和HTML
1 String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>"; 2 Document doc = Jsoup.parse(html);//解析HTML字符串返回一個Document實現 3 Element link = doc.select("a").first();//查找第一個a元素 4 5 String text = doc.body().text(); // "An example link"//取得字符串中的文本 6 String linkHref = link.attr("href"); // "http://example.com/"//取得鏈接地址 7 String linkText = link.text(); // "example""//取得鏈接地址中的文本 8 9 String linkOuterH = link.outerHtml(); 10 // "<a href="http://example.com"><b>example</b></a>" 11 String linkInnerH = link.html(); // "<b>example</b>"//取得鏈接內的html內容
二、與百度鏈接在一起
如何設置百度搜索結果顯示更多條數
【必備參數】:
wd——查詢的關鍵詞(Keyword)
pn——顯示結果的頁數(Page Number)
cl——搜索類型(Class),cl=3為網頁搜索
【可選參數】:
rn——搜索結果顯示條數(Record Number),取值范圍在10--100條之間,缺省設置rn=10