擷取html內容之後
會需要對其內容作修改
這篇就介紹如下
1. 官網https://jsoup.org/cookbook/
2. 屬性和class
a. 添加屬性
語法: Elements或Element名稱.attr(屬性名稱, 屬性值)
其中用Elements則是全部Element都添加
b. 移除屬性
語法:Elements或Element名稱.removeAttr(屬性名稱)
其中用Elements則是全部Element都移除
c. 添加class
語法: Elements或Element名稱.addClass(class值)
其中用Elements則是全部Element都添加
d. 移除屬性
語法:Elements或Element名稱.removeClass(class值)
其中用Elements則是全部Element都移除, 但是class這字會保留
//添加屬性
contents.attr("rel", "nofollow"); //<p rel="nofollow">Line 1.</p>
System.out.println( contents.toString() );
//移除屬性
contents.removeAttr("rel"); //<p>Line 1.</p>
System.out.println( contents.toString() );
//添加class
contents.addClass("round-box"); //<p class="round-box">Line 1.</p>
System.out.println( contents.toString() );
//移除class
contents.removeClass("round-box"); //<p class="">Line 1.</p>
System.out.println( contents.toString() );
3. 文字內容
a. 替換文字內容
語法: Elements或Element名稱.html(內容值)
其中用Elements則是全部Element都添加
b. 在原內容前面加文字
語法:Elements或Element名稱.prepend(內容值)
其中用Elements則是全部Element都添加
c. 在原內容後面加文字
語法: Elements或Element名稱append(內容值)
其中用Elements則是全部Element都添加
d. 移除屬性
語法:Element名稱.text(內容值)
這邊只有Element內可用
//替換內容文字
contents.html("<p>Line 4.</p>"); //<p class=""><p>Line 4.</p></p>
System.out.println( contents.toString() );
//在原內容前面加文字
contents.prepend("<a>prepend</a>");
//<p class=""><a>prepend</a><p>Line 4.</p></p>
System.out.println( contents.toString() );
//在原內容後面加文字
contents.append("<b>append</b>");
//<p class=""><a>prepend</a><p>Line 4.</p><b>append</b></p>
System.out.println( contents.toString() );
Element content = contents.first();
//清空原有的內容用新文字替換
content.text("new"); //<p class="">new</p>
System.out.println( content.toString() );