文章參考學(xué)習(xí)后總結(jié)
參考文章
https://www.yiibai.com/jsoup/jsoup-quick-start.html#article-start
https://blog.csdn.net/u010814849/article/details/52526582
獲取對(duì)象方式:
方法 | 描述 | case |
---|---|---|
static Connection connect(String url) | 創(chuàng)建并返回URL的連接 | case1 |
static Document parse(File in, String charsetName) | 將指定的字符集文件解析成文檔伊脓。 | case2 |
static Document parse(String html) | 將給定的html代碼解析成文檔床绪。 | case3 |
static String clean(String bodyHtml, Whitelist whitelist) | 從輸入HTML返回安全的HTML凉唐,通過(guò)解析輸入HTML并通過(guò)允許的標(biāo)簽和屬性的白名單進(jìn)行過(guò)濾 | case4 |
對(duì)應(yīng)case1极颓、case2盅藻、case3购桑、case4:
public static void main(String[] args) throws Exception {
//case1:Jsoup.connect從網(wǎng)頁(yè)獲取title
Document case1 = Jsoup.connect("http://www.baidu.com").get();
System.out.println(case1.title());
//打印內(nèi)容“百度一下,你就知道”
//case2:Jsoup.parse從文檔獲取title
Document case2 = Jsoup.parse( new File( "D:/temp/index.html" ) , "utf-8" );
System.out.println(case2.title());
//打印內(nèi)容“百度一下氏淑,你就知道”
//case3:Jsoup.parse從網(wǎng)頁(yè)獲取title
String html = "<html><head><title>百度一下勃蜘,你就知道</title></head>"
+ "<body><p>Parsed HTML into a doc.</p></body></html>";
Document case3 = Jsoup.parse(html);
System.out.println(case3.title());
//打印內(nèi)容“百度一下,你就知道”
//case4: Jsoup.clean
String dirtyHTML = "<p><a onclick='sendCookiesToMe()'>Link</a></p>";
String cleanHTML = Jsoup.clean(dirtyHTML, Whitelist.basic());
System.out.println(cleanHTML);
// 執(zhí)行后輸出結(jié)果如下<p><a rel="nofollow">Link</a></p>
}
方法總結(jié)
(Document Elements Element) 公用方法:
Document document = Jsoup.connect("https://www.yiibai.com/").get();
//getElementById(String idName) 根據(jù)id獲取Element
Element formElement = document.getElementById("footer-copyright");
//document.text() 打印所有內(nèi)容
System.out.println(document.text());
//getElementsByTag 根據(jù)標(biāo)簽屬性獲燃俨小(例如缭贡,input,Strong)
Element formElement1=formElement.getElementsByTag("strong").first();
System.out.println(formElement1.text());
// 根絕class獲取Elements
Element formElement = doc.getElementsByClass("fixed-btn").first();
System.out.println(formElement);
//<div class="fixed-btn"> </div>
//attr(String name,String values)在獲取標(biāo)簽后增加屬性
formElement1.attr("hi","我要替換");
//替換后為
System.out.println(formElement1);
//打印信息: <strong hi="我要替換"><a target="_blank">易百教程</a></strong>
//Jsoup.clean
String dirtyHTML = "<p><a onclick='sendCookiesToMe()'>Link</a></p>";
String cleanHTML = Jsoup.clean(dirtyHTML, Whitelist.basic());
System.out.println(cleanHTML);
// 執(zhí)行后輸出結(jié)果如下<p><a rel="nofollow">Link</a></p>
//根據(jù)標(biāo)簽里面的熟悉values獲取 Element
// Elementz 值為<meta name="keywords" content="VBScript, MATLAB, EJB, IPv6, IPv4, 電子商務(wù), PostgreSQL, SQLite, SDLC, Assembly, 操作系統(tǒng)">
String keywords = doc.select("meta[name=keywords]").first().attr("content");
String keywords1 = doc.select("meta[name=keywords]").attr("content");
System.out.println("Meta keyword : " + keywords);
//打印內(nèi)容為 Meta keyword : VBScript, MATLAB, EJB, IPv6, IPv4, 電子商務(wù), PostgreSQL, SQLite, SDLC, Assembly, 操作系統(tǒng),
//獲取圖片Element 并打印相關(guān)信息
Elements images = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
for (Element image : images) {
System.out.println("src : " + image.attr("src"));
System.out.println("height : " + image.attr("height")+"width : " + image.attr("width")+"alt : " + image.attr("alt"));
}
//獲取input并打印key和values
Elements inputElements = doc.getElementsByTag("input");
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
System.out.println("Param name: "+key+" \nParam value: "+value);
}
//獲取網(wǎng)頁(yè)title
String title = doc.title();
System.out.println("title is: " + title);
//打印內(nèi)容“title is: 易百教程? - 專注于IT教程和實(shí)例”
//要獲取網(wǎng)頁(yè)中的所有鏈接辉懒,請(qǐng)使用以下代碼阳惹。
Document document = Jsoup.connect("https://www.baidu.com/").get();
Elements links = document.select("a[href]");
//獲取其中一個(gè)Element為:<a target="_blank" class="mnav">新聞</a>
for (Element link : links)
{
//獲取Element里面的 hrep和text
System.out.println("link : " + link.attr("href"));
//使用 abs:獲得決定路徑
//String absHref = link.attr("abs:href");
System.out.println("text : " + link.text());
}
Elements links = doc.select("a[href]"); //帶有href屬性的a元素
Elements pngs = doc.select("img[src$=.png]"); //擴(kuò)展名為.png的圖片
Element masthead = doc.select("div.fixed-btn").first();//class等于fixed-btn的div標(biāo)簽
Element masthead = doc.select("div#footer-copyright").first();//id等于footer-copyright的div標(biāo)簽
//參考Selector選擇器 基本用法 組合器
Elements resultLinks = doc.select("h3.r > a"); //在h3元素之后的a元素
System.out.println(masthead);
文本修改:
Element doch =Jsoup.parse("<div></div>").select("div").first();
System.out.println(doch);
//打印=<div></div>
//增加text
doch.text("TEST");
System.out.println(doch);
//打印<div>TEST</div>
//text前面增加
doch.prepend("前面添加");
System.out.println(doch);
//打印<div> 前面添加TEST </div>
//text后面增加
doch.append("后面添加");
//打印<div> 前面添加TEST后面添加 </div>
System.out.println(doch);
//根據(jù)html 獲取所有表單中的form的action 和input的name
public static Map getJdPayH5(String respone){
Map reqMap2 = new HashMap();
Document doc = Jsoup.parse(respone);
System.out.println(doc);
reqMap2.put("requestUrl",doc.getElementsByTag("form").attr("action").toString());
Elements times_links = doc.getElementsByTag("input");
for(Element a :times_links){
reqMap2.put(a.attr("name"),a.attr("value"));
}
return reqMap2;
}
Connection
Document doc = Jsoup.connect("http://example.com")
.data("query", "Java")
.userAgent("Mozilla")
.cookie("auth", "token")
.timeout(3000)
.post();
查找元素:
getElementById(String id) | id |
---|---|
getElementsByTag(String tag) | 標(biāo)簽名 |
getElementsByClass(String className) | class名 |
getElementsByAttribute(String key) | 屬性 |
siblingElements() | 所有的兄弟元素 |
firstElementSibling() | 第一個(gè)兄弟元素 |
lastElementSibling() | 最后一個(gè)兄弟元素 |
nextElementSibling() | 下一個(gè)兄弟元素 |
previousElementSibling() | 上一個(gè)兄弟元素 |
parent() | 獲取該元素父節(jié)點(diǎn) |
children() | 獲取該元素的子元素 |
child(int index) | 獲取該元素的第幾個(gè)子元素(下標(biāo)從0開始) |
元素?cái)?shù)據(jù)
attr(String key) | 獲取屬性 |
---|---|
attr(String key, String value) | 設(shè)置屬性 |
attributes() | 獲取所有屬性 |
id() | 獲取該元素id |
className() | 獲取該元素class,多個(gè)class之間空格隔開 |
classNames() | 獲取所有元素的class |
text() | 獲取文本內(nèi)容 |
text(String value) | 設(shè)置文本內(nèi)容 |
html() | 獲取元素內(nèi)HTML |
html(String value) | 設(shè)置元素內(nèi)的HTML內(nèi)容 |
outerHtml() | 獲取元素外HTML內(nèi)容 |
data() | 獲取數(shù)據(jù)內(nèi)容(例如:script和style標(biāo)簽) |
tag() | |
tagName() | 獲取元素標(biāo)簽名 |
操作HTML和文本
append(String html) | 添加給定的html到元素末尾 |
---|---|
prepend(String html) | 添加給定html到元素前面 |
appendText(String text) | 創(chuàng)建并添加文本 |
prependText(String text) | 創(chuàng)建并添加文本 |
appendElement(String tagName) | 添加到元素末尾 |
prependElement(String tagName) | 添加到元素前 |
html(String value) | 設(shè)置元素值 |
Selector選擇器 基本用法
tagname | 使用標(biāo)簽名來(lái)定位眶俩,例如 a |
---|---|
ns|tag | 使用命名空間的標(biāo)簽定位莹汤,例如 fb:name 來(lái)查找 <fb:name> 元素 |
#id | 使用元素 id 定位,例如 #logo |
.class | 使用元素的 class 屬性定位颠印,例如 .head |
[attribute] | 使用元素的屬性進(jìn)行定位纲岭,例如 [href] 表示檢索具有 href 屬性的所有元素 |
[^attr] | 使用元素的屬性名前綴進(jìn)行定位,例如 [^data-] 用來(lái)查找 HTML5 的 dataset 屬性 |
[attr=value] | 使用屬性值進(jìn)行定位嗽仪,例如 [width=500] 定位所有 width 屬性值為 500 的元素 |
[attr^=value], [attr$=value], [attr*=value] | 利用匹配屬性值開頭荒勇、結(jié)尾或包含屬性值來(lái)查找元素,比如:[href*=/path/] |
[attr~=regex] | 利用屬性值匹配正則表達(dá)式來(lái)查找元素闻坚,例如img[src~=(?i).(png |jpe?g)] |
* | 定位所有元素 |
Selector選擇器 組合使用
el#id | 定位 id 值某個(gè)元素沽翔,例如 a#logo -> <a id=logo href= … > |
---|---|
el.class | 定位 class 為指定值的元素,例如 div.head -> <div class=head>xxxx</div> |
el[attr] | 定位所有定義了某屬性的元素,例如 a[href] |
以上三個(gè)任意組合 | 例如 a[href]#logo 仅偎、a[name].outerlink |
ancestor child | 查找某個(gè)元素下子元素跨蟹,比如:可以用.body p 查找在"body"元素下的所有 p元素 |
parent > child | 查找某個(gè)父元素下的直接子元素,比如:可以用div.content > p 查找 p 元素橘沥,也可以用body > * 查找body標(biāo)簽下所有直接子元素 |
siblingA + siblingB | 查找在A元素之前第一個(gè)同級(jí)元素B窗轩,比如:div.head + div |
siblingA ~ siblingX | 查找A元素之前的同級(jí)X元素,比如:h1 ~ p |
el, el, el | 多個(gè)選擇器組合座咆,查找匹配任一選擇器的唯一元素痢艺,例如:div.masthead, div.logo |
偽選擇器selectors (表達(dá)式):
:lt(n) | 查找哪些元素的同級(jí)索引值(它的位置在DOM樹中是相對(duì)于它的父節(jié)點(diǎn))小于n,比如:td:lt(3) 表示小于三列的元素 |
---|---|
:gt(n) | 查找哪些元素的同級(jí)索引值大于n``介陶,比如: div p:gt(2)表示哪些div中有包含2個(gè)以上的p元素 |
:eq(n) | 查找哪些元素的同級(jí)索引值與n相等堤舒,比如:form input:eq(1)表示包含一個(gè)input標(biāo)簽的Form元素 |
:has(seletor) | 查找匹配選擇器包含元素的元素,比如:div:has(p)表示哪些div包含了p元素 |
:not(selector) | 查找與選擇器不匹配的元素哺呜,比如: div:not(.logo) 表示不包含 class=logo 元素的所有 div 列表 |
:contains(text) | 查找包含給定文本的元素舌缤,不區(qū)分大不寫,比如: p:contains(jsoup) |
:containsOwn(text) | 查找文本信息完全等于指定條件的元素 |
:matches(regex) | 使用正則表達(dá)式進(jìn)行文本過(guò)濾:div:matches((?i)login) |
:matchesOwn(regex) | 使用正則表達(dá)式找到自身的文本 |