以下示例将展示使用方法设置dom元素的属性,批量更新以及在将HTML字符串解析为Document对象后添加/删除类方法.
语法
Document document = Jsoup.parse(html);Element link = document.select("a").first(); link.attr("href","www.yahoo.com"); link.addClass("header"); link.removeClass("header");
其中
文件 : document对象代表HTML DOM.
Jsoup : 用于解析给定HTML字符串的主类.
html : HTML字符串.
链接 : Element对象表示代表锚标记的html节点元素.
link.attr() : attr(attribute,value)方法将元素属性设置为相应的值.
link.addClass() : addClass(class)方法在class属性下添加类.
link.removeClass() : removeClass(class)方法删除class属性下的类.
描述
元素对象代表一个dom elment并提供各种方法来获取dom元素的属性.
示例
使用您选择的任何编辑器创建以下java程序比方说C:/> jsoup.
JsoupTester.java
import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public class JsoupTester { public static void main(String[] args) { String html = "Sample Title " + "" + "Sample Content
" + "" + "Sample1" + "Sample2" + "Sample3" +"" + "" +""; Document document = Jsoup.parse(html); //Example: set attribute Element link = document.getElementById("googleA"); System.out.println("Outer HTML Before Modification :" + link.outerHtml()); link.attr("href","www.yahoo.com"); System.out.println("Outer HTML After Modification :" + link.outerHtml()); System.out.println("---"); //Example: add class Element div = document.getElementById("sampleDiv"); System.out.println("Outer HTML Before Modification :" + div.outerHtml()); link.addClass("header"); System.out.println("Outer HTML After Modification :" + div.outerHtml()); System.out.println("---"); //Example: remove class Element div1 = document.getElementById("imageDiv"); System.out.println("Outer HTML Before Modification :" + div1.outerHtml()); div1.removeClass("header"); System.out.println("Outer HTML After Modification :" + div1.outerHtml()); System.out.println("---"); //Example: bulk update Elements links = document.select("div.comments a"); System.out.println("Outer HTML Before Modification :" + links.outerHtml()); links.attr("rel", "nofollow"); System.out.println("Outer HTML Before Modification :" + links.outerHtml()); }}" + "
" +"
验证结果
使用 javac编译类编译如下:
C:\jsoup>javac JsoupTester.java现在运行JsoupTester查看结果.
C:\jsoup>java JsoupTester查看结果.
Outer HTML Before Modification :GoogleOuter HTML After Modification :Google---Outer HTML Before Modification :Outer HTML After Modification :---Outer HTML Before Modification :Outer HTML After Modification :
---Outer HTML Before Modification :Sample1Sample2Sample3Outer HTML Before Modification :Sample1Sample2Sample3![]()