Jsoup元件抓取HTML標籤

2021-08-07 06:31:17 字數 2267 閱讀 1116

jsoup可以解析乙個html字串,可以解析乙個url,也可以解析乙個html文字:

1:解析乙個字串

public static void parsehtmltext()
說明:

parse(string html, string baseuri)這方法能夠將輸入的html解析為乙個新的文件 (document),引數 baseuri 是用來將相對 url 轉成絕對url,並指定從哪個**獲取文件。如這個方法不適用,你可以使用parse(string html)方法來解析成html字串如上面的示例。.

只要解析的不是空字串,就能返回乙個結構合理的文件,其中包含(至少) 乙個head和乙個body元素。 

一旦擁有了乙個document,你就可以使用document中適當的方法或它父類elementnode中的方法來取得相關資料。

2:解析乙個body片段

public static void parsehtmlbody()
3:解析乙個html文字

public static void parsehtmlfile() catch (ioexception e) 

}

4:根據url解析html

public static void  parsehtmlurl() catch (ioexception e) 

}

注意:根據url解析html.並且獲取標題(注意此寫法在android中應該將這個方法放在子執行緒中),

connect(string url) 方法建立乙個新的 connection, 和 get() 

取得和解析乙個html檔案。如果從該url獲取html時發生錯誤,便會丟擲 ioexception,應適當處理。

5:獲取html文件中的img標籤

public static void  parsehtmlimgelement()

} catch (ioexception e)

}

注意:e.attr("src")返回的字串不是乙個全路徑,是

列印結果如下:

public static void  parsehtmllinkelement()

} catch (ioexception e)

}

7:選擇器語法查詢元素以及屬性

public static void  selecthtmllinkelement()

for(element e : links)

system.out.println("**************selecthtmllinkelement***************");

for(element e : pngs)

} catch (ioexception e)

}

selector選擇器的使用:

tagname: 通過標籤查詢元素,比如:a

ns|tag: 通過標籤在命名空間查詢元素,比如:可以用 fb|name 語法來查詢 元素

#id: 通過id查詢元素,比如:#logo

.class: 通過class名稱查詢元素,比如:.masthead

[attribute]: 利用屬性查詢元素,比如:[href]

[^attr]: 利用屬性名字首來查詢元素,比如:可以用[^data-] 來查詢帶有html5 dataset屬性的元素

[attr=value]: 利用屬性值來查詢元素,比如:[width=500]

[attr^=value], [attr$=value], [attr*=value]: 利用匹配屬性值開頭、結尾或包含屬性值來查詢元素,比如:[href*=/path/]

[attr~=regex]: 利用屬性值匹配正規表示式來查詢元素,比如: img[src~=(?i)\.(png|jpe?g)]

Jsoup抓取資料

首先我們來看來自 的乙個html片段,了解其結構。class detail style display block class add jrsj plus bookid 609737 em class mark63 href target blank src alt 不死龍帝 style width...

html靜態頁面標籤抓取

最近老總要求搞什麼商品下架問題,就是別人 上的商品下架了,我也要下架,所以我們要通過路徑來判斷這個商品是否下架,自己實現了幾個功能,所有的 基本上都還行,就有寫需要修改語言的 還可以訪問 htmlagilitypack.htmldocument htmldocument new htmlagilit...

用Jsoup實現html中標籤替換

我的解決的方法就是在顯示之前把img標籤的src位址換成絕對位址,找了一下選擇了大家很推崇的jsoup newsbody doc.tostring 方法 可以使用屬性設定方法 element.attr string key,string value 和 elements.attr string ke...