標籤:des style class blog code java
jsoup簡介
jsoup是一款HTML解析器,可用與解析URL地址、HTML文本內同等,操作類似於jQuery,可通過DOM尋找資料,操作資料, 使用時需引入jsoup jar
jsoup可以從包含字串、url及本地檔案載入html文檔,產生Document對象,通過Document對象即可操作文檔中的資料
eg:
//通過urlDocument doc = Jsoup.connect("http://www.cnblogs.com/wishyouhappy").get();//通過html 字串String html = "<html><head></head> <body><p>#####</p></body></html>";Document doc = Jsoup.parse(html);//通過檔案載入,第三個參數指示baseURL File input = new File("D:/test.html"); Document doc = Jsoup.parse(input,"UTF-8","http://www.cnblogs.com/wishyouhappy");
資料操作eg:
Document doc = Jsoup.connect("http://www.cnblogs.com/wishyouhappy").get();System.out.println(doc.title());
常用函數
parse相關:
static Document parse(File in, String charsetName)static Document parse(File in, String charsetName, String baseUri)static Document parse(InputStream in, String charsetName, String baseUri)static Document parse(String html)static Document parse(String html, String baseUri) static Document parse(URL url, int timeoutMillis)static Document parseBodyFragment(String bodyHtml)static Document parseBodyFragment(String bodyHtml, String baseUri)
url connect相關:
Connection connect(String url) //根據給定的url(必須是http或https)來建立串連Connection cookie(String name, String value) //發送請求時放置cookie Connection data(Map<String,String> data) //傳遞請求參數 Connection data(String... keyvals) //傳遞請求參數Document get() //以get方式發送請求並對返回結果進行解析Document post()//以post方式發送請求並對返回結果進行解析 Connection userAgent(String userAgent) Connection header(String name, String value) //添加要求標頭Connection referrer(String referrer) //佈建要求來源
擷取html元素:
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() text() //獲得文本值text(String value) //設定文本值html() //擷取html html(String value)//設定htmlouterHtml()data()tag() //獲得tag tagName() //獲得tagname
添加元素:
append(String html), prepend(String html)appendText(String text), prependText(String text)appendElement(String tagName),prependElement(String tagName)
選取器:
| tagname |
使用標籤名來定位,例如 a |
| ns|tag |
使用命名空間的標籤定位,例如 fb:name 來尋找 <fb:name> 元素 |
| #id |
使用元素 id 定位,例如 #logo |
| .class |
使用元素的 class 屬性定位,例如 .head |
| [attribute] |
使用元素的屬性進行定位,例如 [href] 表示檢索具有 href 屬性的所有元素 |
| [^attr] |
使用元素的屬性名稱首碼進行定位,例如 [^data-] 用來尋找 HTML5 的 dataset 屬性 |
| [attr=value] |
使用屬性值進行定位,例如 [width=500] 定位所有 width 屬性值為 500 的元素 |
| [attr^=value], [attr$=value], [attr*=value] |
這三個文法分別代表,屬性以 value 開頭、結尾以及包含 |
| [attr~=regex] |
使用Regex進行屬性值的過濾,例如 img[src~=(?i)\.(png|jpe?g)] |
| * |
定位所有元素 |
| el#id |
定位 id 值某個元素,例如 a#logo -> <a id=logo href= … > |
| el.class |
定位 class 為指定值的元素,例如 div.head -> <div class="head">xxxx</div> |
| el[attr] |
定位所有定義了某屬性的元素,例如 a[href] |
| 以上三個任意組合 |
例如 a[href]#logo 、a[name].outerlink |
| ancestor child |
這五種都是元素之間組合關係的選取器文法,其中包括父子關係、合并關係和層次關係。 |
| parent > child |
|
| siblingA + siblingB |
|
| siblingA ~ siblingX |
|
| :lt(n) |
例如 td:lt(3) 表示 小於三列 |
| :gt(n) |
div p:gt(2) 表示 div 中包含 2 個以上的 p |
| :eq(n) |
form input:eq(1) 表示只包含一個 input 的表單 |
| :has(seletor) |
div:has(p) 表示包含了 p 元素的 div |
| :not(selector) |
div:not(.logo) 表示不包含 class="logo" 元素的所有 div 列表 |
| :contains(text) |
包含某文本的元素,不區分大小寫,例如 p:contains(oschina) |
| :containsOwn(text) |
文本資訊完全等於指定條件的過濾 |
| :matches(regex) |
使用Regex進行文本過濾:div:matches((?i)login) |
| :matchesOwn(regex) |
使用Regex找到自身的文本
|
例子:
package jsoup;/** * * 建立人:wish * 建立時間:2014年6月13日 下午1:22:49 */import java.io.IOException;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public class BlogCatch { /** * main * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // getArticleTitle("http://www.cnblogs.com/wishyouhappy"); Document doc = Jsoup.connect("http://www.cnblogs.com/wishyouhappy") .data("query", "Java") // 請求參數 .userAgent("I ’ m jsoup") // 設定 User-Agent .cookie("auth", "token") // 設定 cookie .timeout(3000) // 設定連線逾時時間 .post(); System.out.println(doc.title()); } /** * 擷取指定HTML 文檔指定的body * 傳入html string * @throws IOException */ @SuppressWarnings("unused") private static void getBlogBodyByString(String html) { Document doc = Jsoup.parse(html); System.out.println(doc.body()); } /** * * getBlogBodyByURL 通過url擷取文檔body * @param url * @return * */ @SuppressWarnings("unused") private static void getBlogBodyByURL(String url) throws IOException { // 從 URL 直接載入 HTML 文檔 Document doc2 = Jsoup.connect(url).get(); String title = doc2.body().toString(); System.out.println(title); } /** * * article 擷取部落格上的文章標題和連結 * @param url * @return * @Exception 異常對象 */ public static void getArticleTitle(String url) { Document doc; try { doc = Jsoup.connect(url).get(); Elements ListDiv = doc.getElementsByAttributeValue("class","postTitle"); for (Element element :ListDiv) { Elements links = element.getElementsByTag("a"); for (Element link : links) { String linkHref = link.attr("href"); String linkText = link.text().trim(); System.out.println(linkHref); System.out.println(linkText); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * * getBlog 擷取指定部落格文章的內容 * @param name * @return * @Exception 異常對象 */ public static void getBlog(String url) { Document doc; try { doc = Jsoup.connect(url).get(); Elements ListDiv = doc.getElementsByAttributeValue("class","postBody"); for (Element element :ListDiv) { System.out.println(element.html()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}