Jsoup解析Html中文文档

Jsoup解析Html中文文档

jsoup 简介
Java 程序在解析 HTML 文档时,相信大家都接触过 htmlparser 这个开源项目,我曾经在 IBM DW 上发表过两篇关于 htmlparser 的文章,分别是:从 HTML 中攫取你所需的信息和 扩展 HTMLParser 对自定义标签的处理能力。但现在我已经不再使用 htmlparser 了,原因是 htmlparser 很少更新,但最重要的是有了 jsoup 。
jsoup 是一款 Java 的 HTML 解析器,可直接解析某个 URL 地址、HTML 文本内容。它提供了一套非常省力的 API,可通过 DOM,CSS 以及类似于 jQuery 的操作方法来取出和操作数据。
jsoup 的主要功能如下:
1. 从一个 URL,文件或字符串中解析 HTML;
2. 使用 DOM 或 CSS 选择器来查找、取出数据;
3. 可操作 HTML 元素、属性、文本;

官网地址:http://www.open-open.com/jsoup/     

jsoup Cookbook(中文版)
入门
1.解析和遍历一个html文档
输入
2.解析一个html字符串
3.解析一个body片断
4.根据一个url加载Document对象
5.根据一个文件加载Document对象
数据抽取
6.使用dom方法来遍历一个Document对象
7.使用选择器语法来查找元素
8.从元素集合抽取属性、文本和html内容
9.URL处理
10.程序示例:获取所有链接
数据修改
11.设置属性值
12.设置元素的html内容
13.设置元素的文本内容
html清理
14.消除不受信任的html (来防止xss攻击)

1.解析和遍历一个HTML文档
如何解析一个HTML文档:

?
1
2
3
String html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p></body></html>" ;
Document doc = Jsoup.parse(html);

  (更详细内容可查看 解析一个HTML字符串.)

其解析器能够尽最大可能从你提供的HTML文档来创见一个干净的解析结果,无论HTML的格式是否完整。比如它可以处理:

没有关闭的标签 (比如: <p>Lorem <p>Ipsum parses to <p>Lorem</p> <p>Ipsum</p>)
隐式标签 (比如. 它可以自动将 <td>Table data</td>包装成<table><tr><td>?)
创建可靠的文档结构(html标签包含head 和 body,在head只出现恰当的元素)
一个文档的对象模型
文档由多个Elements和TextNodes组成 (以及其它辅助nodes:详细可查看:nodes package tree).
其继承结构如下:Document继承Element继承Node. TextNode继承 Node.
一个Element包含一个子节点集合,并拥有一个父Element。他们还提供了一个唯一的子元素过滤列表。
参见
数据抽取:DOM遍历
数据抽取:Selector syntax

2.解析一个HTML字符串
存在问题
来自用户输入,一个文件或一个网站的HTML字符串,你可能需要对它进行解析并取其内容,或校验其格式是否完整,或想修改它。怎么办?jsonu能够帮你轻松解决这些问题

解决方法
使用静态Jsoup.parse(String html) 方法或 Jsoup.parse(String html, String baseUri)示例代码:

?
1
2
3
String html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p></body></html>" ;
Document doc = Jsoup.parse(html);

  描述

parse(String html, String baseUri) 这方法能够将输入的HTML解析为一个新的文档 (Document),参数 baseUri 是用来将相对 URL 转成绝对URL,并指定从哪个网站获取文档。如这个方法不适用,你可以使用 parse(String html) 方法来解析成HTML字符串如上面的示例。.

只要解析的不是空字符串,就能返回一个结构合理的文档,其中包含(至少) 一个head和一个body元素。

一旦拥有了一个Document,你就可以使用Document中适当的方法或它父类 Element和Node中的方法来取得相关数据。

 

3.解析一个body片断

问题
假如你有一个HTML片断 (比如. 一个 div 包含一对 p 标签; 一个不完整的HTML文档) 想对它进行解析。这个HTML片断可以是用户提交的一条评论或在一个CMS页面中编辑body部分。

办法
使用Jsoup.parseBodyFragment(String html)方法.

?
1
2
3
String html = "<div><p>Lorem ipsum.</p>" ;
Document doc = Jsoup.parseBodyFragment(html);
Element body = doc.body();

  说明

parseBodyFragment 方法创建一个空壳的文档,并插入解析过的HTML到body元素中。假如你使用正常的 Jsoup.parse(String html) 方法,通常你也可以得到相同的结果,但是明确将用户输入作为 body片段处理,以确保用户所提供的任何糟糕的HTML都将被解析成body元素。

Document.body() 方法能够取得文档body元素的所有子元素,与 doc.getElementsByTag("body")相同。

保证安全Stay safe
假如你可以让用户输入HTML内容,那么要小心避免跨站脚本攻击。利用基于 Whitelist 的清除器和 clean(String bodyHtml, Whitelist whitelist)方法来清除用户输入的恶意内容。

4.从一个URL加载一个Document

存在问题

你需要从一个网站获取和解析一个HTML文档,并查找其中的相关数据。你可以使用下面解决方法:

解决方法

使用 Jsoup.connect(String url)方法:

?
1
2
Document doc = Jsoup.connect( "http://example.com/" ).get();
String title = doc.title();

  说明

connect(String url) 方法创建一个新的 Connection, 和 get() 取得和解析一个HTML文件。如果从该URL获取HTML时发生错误,便会抛出 IOException,应适当处理。

Connection 接口还提供一个方法链来解决特殊请求,具体如下:

?
1
2
3
4
5
6
Document doc = Jsoup.connect( "http://example.com" )
   .data( "query" , "Java" )
   .userAgent( "Mozilla" )
   .cookie( "auth" , "token" )
   .timeout( 3000 )
   .post();

  这个方法只支持Web URLs (httphttps 协议); 假如你需要从一个文件加载,可以使用 parse(File in, String charsetName) 代替。

5.从一个文件加载一个文档

问题

在本机硬盘上有一个HTML文件,需要对它进行解析从中抽取数据或进行修改。

办法

可以使用静态 Jsoup.parse(File in, String charsetName, String baseUri) 方法:

?
1
2
File input = new File( "/tmp/input.html" );
Document doc = Jsoup.parse(input, "UTF-8" , "http://example.com/" );

  说明

parse(File in, String charsetName, String baseUri) 这个方法用来加载和解析一个HTML文件。如在加载文件的时候发生错误,将抛出IOException,应作适当处理。

baseUri 参数用于解决文件中URLs是相对路径的问题。如果不需要可以传入一个空的字符串。

另外还有一个方法parse(File in, String charsetName) ,它使用文件的路径做为 baseUri。 这个方法适用于如果被解析文件位于网站的本地文件系统,且相关链接也指向该文件系统。

6.使用DOM方法来遍历一个文档

问题

你有一个HTML文档要从中提取数据,并了解这个HTML文档的结构。

方法

将HTML解析成一个Document之后,就可以使用类似于DOM的方法进行操作。示例代码:

?
1
2
3
4
5
6
7
8
9
File input = new File( "/tmp/input.html" );
Document doc = Jsoup.parse(input, "UTF-8" , "http://example.com/" );
 
Element content = doc.getElementById( "content" );
Elements links = content.getElementsByTag( "a" );
for (Element link : links) {
   String linkHref = link.attr( "href" );
   String linkText = link.text();
}

  说明

Elements这个对象提供了一系列类似于DOM的方法来查找元素,抽取并处理其中的数据。具体如下:

查找元素

元素数据

操作HTML和文本

7.使用选择器语法来查找元素

问题

你想使用类似于CSS或jQuery的语法来查找和操作元素。

方法

可以使用Element.select(String selector) 和 Elements.select(String selector) 方法实现:

?
1
2
3
4
5
6
7
8
9
10
11
File input = new File( "/tmp/input.html" );
Document doc = Jsoup.parse(input, "UTF-8" , "http://example.com/" );
 
Elements links = doc.select( "a[href]" ); //带有href属性的a元素
Elements pngs = doc.select( "img[src$=.png]" );
   //扩展名为.png的图片
 
Element masthead = doc.select( "div.masthead" ).first();
   //class等于masthead的div标签
 
Elements resultLinks = doc.select( "h3.r > a" ); //在h3元素之后的a元素

 说明

jsoup elements对象支持类似于CSS (或jquery)的选择器语法,来实现非常强大和灵活的查找功能。.

这个select 方法在DocumentElement,或Elements对象中都可以使用。且是上下文相关的,因此可实现指定元素的过滤,或者链式选择访问。

Select方法将返回一个Elements集合,并提供一组方法来抽取和处理结果。

Selector选择器概述

  • tagname: 通过标签查找元素,比如:a
  • ns|tag: 通过标签在命名空间查找元素,比如:可以用 fb|name 语法来查找 <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)]
  • *: 这个符号将匹配所有元素

Selector选择器组合使用

  • el#id: 元素+ID,比如: div#logo
  • el.class: 元素+class,比如: div.masthead
  • el[attr]: 元素+class,比如: a[href]
  • 任意组合,比如:a[href].highlight
  • ancestor child: 查找某个元素下子元素,比如:可以用.body p 查找在"body"元素下的所有 p元素
  • parent > child: 查找某个父元素下的直接子元素,比如:可以用div.content > p 查找 p 元素,也可以用body > * 查找body标签下所有直接子元素
  • siblingA + siblingB: 查找在A元素之前第一个同级元素B,比如:div.head + div
  • siblingA ~ siblingX: 查找A元素之前的同级X元素,比如:h1 ~ p
  • el, el, el:多个选择器组合,查找匹配任一选择器的唯一元素,例如:div.masthead, div.logo

伪选择器selectors

  • :lt(n): 查找哪些元素的同级索引值(它的位置在DOM树中是相对于它的父节点)小于n,比如:td:lt(3) 表示小于三列的元素
  • :gt(n):查找哪些元素的同级索引值大于n,比如: div p:gt(2)表示哪些div中有包含2个以上的p元素
  • :eq(n): 查找哪些元素的同级索引值与n相等,比如:form input:eq(1)表示包含一个input标签的Form元素
  • :has(seletor): 查找匹配选择器包含元素的元素,比如:div:has(p)表示哪些div包含了p元素
  • :not(selector): 查找与选择器不匹配的元素,比如: div:not(.logo) 表示不包含 class="logo" 元素的所有 div 列表
  • :contains(text): 查找包含给定文本的元素,搜索不区分大不写,比如: p:contains(jsoup)
  • :containsOwn(text): 查找直接包含给定文本的元素
  • :matches(regex): 查找哪些元素的文本匹配指定的正则表达式,比如:div:matches((?i)login)
  • :matchesOwn(regex): 查找自身包含文本匹配指定正则表达式的元素
  • 注意:上述伪选择器索引是从0开始的,也就是说第一个元素索引值为0,第二个元素index为1等

可以查看Selector API参考来了解更详细的内容

8.从元素抽取属性,文本和HTML

问题

在解析获得一个Document实例对象,并查找到一些元素之后,你希望取得在这些元素中的数据。

方法

示例:

?
1
2
3
4
5
6
7
8
9
10
11
String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>" ;
Document doc = Jsoup.parse(html); //解析HTML字符串返回一个Document实现
Element link = doc.select( "a" ).first(); //查找第一个a元素
 
String text = doc.body().text(); // "An example link"//取得字符串中的文本
String linkHref = link.attr( "href" ); // "http://example.com/"//取得链接地址
String linkText = link.text(); // "example""//取得链接地址中的文本
 
String linkOuterH = link.outerHtml();
     // "<a href="http://example.com"><b>example</b></a>"
String linkInnerH = link.html(); // "<b>example</b>"//取得链接内的html内容

  说明

上述方法是元素数据访问的核心办法。此外还其它一些方法可以使用:

这些访问器方法都有相应的setter方法来更改数据.

参见

9.处理URLs

问题

你有一个包含相对URLs路径的HTML文档,需要将这些相对路径转换成绝对路径的URLs。

方法

  1. 在你解析文档时确保有指定base URI,然后
  2. 使用 abs: 属性前缀来取得包含base URI的绝对路径。代码如下: 
    ?
    1
    2
    3
    4
    5
    Document doc = Jsoup.connect( "http://www.open-open.com" ).get();
     
    Element link = doc.select( "a" ).first();
    String relHref = link.attr( "href" ); // == "/"
    String absHref = link.attr( "abs:href" ); // "http://www.open-open.com/"

      说明

在HTML元素中,URLs经常写成相对于文档位置的相对路径: <a href="/download">...</a>. 当你使用 Node.attr(String key) 方法来取得a元素的href属性时,它将直接返回在HTML源码中指定定的值。

假如你需要取得一个绝对路径,需要在属性名前加 abs: 前缀。这样就可以返回包含根路径的URL地址attr("abs:href")

因此,在解析HTML文档时,定义base URI非常重要。

如果你不想使用abs: 前缀,还有一个方法能够实现同样的功能 Node.absUrl(String key)

10.示例程序: 获取所有链接

这个示例程序将展示如何从一个URL获得一个页面。然后提取页面中的所有链接、图片和其它辅助内容。并检查URLs和文本信息。

运行下面程序需要指定一个URLs作为参数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
 
import java.io.IOException;
 
/**
  * Example program to list links from a URL.
  */
public class ListLinks {
     public static void main(String[] args) throws IOException {
        // Validate.isTrue(args.length == 1, "usage: supply url to fetch");
         String url = "http://news.ycombinator.com/" ;
         print( "Fetching %s..." , url);
 
         Document doc = Jsoup.connect(url).get();
         Elements links = doc.select( "a[href]" ); //"a[href]" //带有href属性的a元素
         Elements media = doc.select( "[src]" );   //利用属性查找元素,比如:[href]
         Elements imports = doc.select( "link[href]" );
 
         print( "\nMedia: (%d)" , media.size());
         for (Element src : media) {
             if (src.tagName().equals( "img" ))
                 print( " * %s: <%s> %sx%s (%s)" ,
                         src.tagName(), src.attr( "abs:src" ), src.attr( "width" ), src.attr( "height" ),
                         trim(src.attr( "alt" ), 20 )); //src.attr("src")结果:<y18.gif> 18x18 () 
                                                    //src.attr("abs:src")结果:<https://news.ycombinator.com/y18.gif> 18x18 ()
             else
                 print( " * %s: <%s>" , src.tagName(), src.attr( "abs:src" ));
         }
 
         print( "\nImports: (%d)" , imports.size());
         for (Element link : imports) {
             print( " * %s <%s> (%s)" , link.tagName(),link.attr( "abs:href" ), link.attr( "rel" ));
         }
 
         print( "\nLinks: (%d)" , links.size());
         for (Element link : links) {
             print( " * a: <%s>  (%s)" , link.attr( "abs:href" ), trim(link.text(), 35 ));
         }
     }
 
     private static void print(String msg, Object... args) {
         System.out.println(String.format(msg, args));
     }
 
     private static String trim(String s, int width) {
         if (s.length() > width)
             return s.substring( 0 , width- 1 ) + "." ;
         else
             return s;
     }
}
//org/jsoup/examples/ListLinks.java

  示例输入结果:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Fetching http: //news.ycombinator.com/...
 
Media: ( 38 )
  * img: <http: //ycombinator.com/images/y18.gif> 18x18 ()
  * img: <http: //ycombinator.com/images/s.gif> 10x1 ()
  * img: <http: //ycombinator.com/images/grayarrow.gif> x ()
  * img: <http: //ycombinator.com/images/s.gif> 0x10 ()
  * script: <http: //www.co2stats.com/propres.php?s=1138>
  * img: <http: //ycombinator.com/images/s.gif> 15x1 ()
  * img: <http: //ycombinator.com/images/hnsearch.png> x ()
  * img: <http: //ycombinator.com/images/s.gif> 25x1 ()
  * img: <http: //mixpanel.com/site_media/images/mixpanel_partner_logo_borderless.gif> x (Analytics by Mixpan.)
  
Imports: ( 2 )
  * link <http: //ycombinator.com/news.css> (stylesheet)
  * link <http: //ycombinator.com/favicon.ico> (shortcut icon)
  
Links: ( 141 )
  * a: <http: //ycombinator.com>  ()
  * a: <http: //news.ycombinator.com/news>  (Hacker News)
  * a: <http: //news.ycombinator.com/newest>  (new)
  * a: <http: //news.ycombinator.com/newcomments>  (comments)
  * a: <http: //news.ycombinator.com/leaders>  (leaders)
  * a: <http: //news.ycombinator.com/jobs>  (jobs)
  * a: <http: //news.ycombinator.com/submit>  (submit)
  * a: <http: //news.ycombinator.com/x?fnid=JKhQjfU7gW>  (login)
  * a: <http: //news.ycombinator.com/vote?for=1094578&dir=up&whence=%6e%65%77%73>  ()
  * a: <http: //www.readwriteweb.com/archives/facebook_gets_faster_debuts_homegrown_php_compiler.php?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+readwriteweb+%28ReadWriteWeb%29&utm_content=Twitter>  (Facebook speeds up PHP)
  * a: <http: //news.ycombinator.com/user?id=mcxx>  (mcxx)
  * a: <http: //news.ycombinator.com/item?id=1094578>  (9 comments)
  * a: <http: //news.ycombinator.com/vote?for=1094649&dir=up&whence=%6e%65%77%73>  ()
  * a: <http: //groups.google.com/group/django-developers/msg/a65fbbc8effcd914>  ("Tough. Django produces XHTML.")
  * a: <http: //news.ycombinator.com/user?id=andybak>  (andybak)
  * a: <http: //news.ycombinator.com/item?id=1094649>  (3 comments)
  * a: <http: //news.ycombinator.com/vote?for=1093927&dir=up&whence=%6e%65%77%73>  ()
  * a: <http: //news.ycombinator.com/x?fnid=p2sdPLE7Ce>  (More)
  * a: <http: //news.ycombinator.com/lists>  (Lists)
  * a: <http: //news.ycombinator.com/rss>  (RSS)
  * a: <http: //ycombinator.com/bookmarklet.html>  (Bookmarklet)
  * a: <http: //ycombinator.com/newsguidelines.html>  (Guidelines)
  * a: <http: //ycombinator.com/newsfaq.html>  (FAQ)
  * a: <http: //ycombinator.com/newsnews.html>  (News News)
  * a: <http: //news.ycombinator.com/item?id=363>  (Feature Requests)
  * a: <http: //ycombinator.com>  (Y Combinator)
  * a: <http: //ycombinator.com/w2010.html>  (Apply)
  * a: <http: //ycombinator.com/lib.html>  (Library)
  * a: <http: //www.webmynd.com/html/hackernews.html>  ()
  * a: <http: //mixpanel.com/?from=yc>  ()

  

11.设置属性的值

问题

在你解析一个Document之后可能想修改其中的某些属性值,然后再保存到磁盘或都输出到前台页面。

方法

可以使用属性设置方法 Element.attr(String key, String value), 和 Elements.attr(String key, String value).

假如你需要修改一个元素的 class 属性,可以使用 Element.addClass(String className) 和Element.removeClass(String className) 方法。

Elements 提供了批量操作元素属性和class的方法,比如:要为div中的每一个a元素都添加一个rel="nofollow" 可以使用如下方法:

?
1
doc.select( "div.comments a" ).attr( "rel" , "nofollow" );

  说明

Element中的其它方法一样,attr 方法也是返回当 Element (或在使用选择器是返回 Elements 集合)。这样能够很方便使用方法连用的书写方式。比如:

?
1
doc.select( "div.masthead" ).attr( "title" , "jsoup" ).addClass( "round-box" );

  

12.设置一个元素的HTML内容

问题

你需要一个元素中的HTML内容

方法

可以使用Element中的HTML设置方法具体如下:

?
1
2
3
4
5
6
7
8
9
Element div = doc.select( "div" ).first(); // <div></div>
div.html( "<p>lorem ipsum</p>" ); // <div><p>lorem ipsum</p></div>
div.prepend( "<p>First</p>" ); //在div前添加html内容
div.append( "<p>Last</p>" ); //在div之后添加html内容
// 添完后的结果: <div><p>First</p><p>lorem ipsum</p><p>Last</p></div>
 
Element span = doc.select( "span" ).first(); // <span>One</span>
span.wrap( "<li><a href='http://example.com/'></a></li>" );
// 添完后的结果: <li><a href="http://example.com"><span>One</span></a></li>

  说明

参见

可以查看API参考文档中 Element.prependElement(String tag)Element.appendElement(String tag) 方法来创建新的元素并作为文档的子元素插入其中。

13.设置元素的文本内容

问题

你需要修改一个HTML文档中的文本内容

方法

可以使用Element的设置方法::

?
1
2
3
4
5
Element div = doc.select( "div" ).first(); // <div></div>
div.text( "five > four" ); // <div>five > four</div>
div.prepend( "First " );
div.append( " Last" );
// now: <div>First five > four Last</div>

  说明

文本设置方法与 HTML setter 方法一样:

对于传入的文本如果含有像 <> 等这样的字符,将以文本处理,而非HTML。

14.消除不受信任的HTML (来防止XSS攻击)

问题

在做网站的时候,经常会提供用户评论的功能。有些不怀好意的用户,会搞一些脚本到评论内容中,而这些脚本可能会破坏整个页面的行为,更严重的是获取一些机要信息,此时需要清理该HTML,以避免跨站脚本cross-site scripting攻击(XSS)。

方法

使用jsoup HTML Cleaner 方法进行清除,但需要指定一个可配置的 Whitelist

?
1
2
3
4
String unsafe =
   "<p><a href='http://example.com/' onclick='stealCookies()'>Link</a></p>" ;
String safe = Jsoup.clean(unsafe, Whitelist.basic());
// now: <p><a href="http://example.com/" rel="nofollow">Link</a></p>

  说明

XSS又叫CSS (Cross Site Script) ,跨站脚本攻击。它指的是恶意攻击者往Web页面里插入恶意html代码,当用户浏览该页之时,嵌入其中Web里面的html代码会被执行,从而达到恶意攻击用户的特殊目的。XSS属于被动式的攻击,因为其被动且不好利用,所以许多人常忽略其危害性。所以我们经常只让用户输入纯文本的内容,但这样用户体验就比较差了。

一个更好的解决方法就是使用一个富文本编辑器WYSIWYG如CKEditor 和 TinyMCE。这些可以输出HTML并能够让用户可视化编辑。虽然他们可以在客户端进行校验,但是这样还不够安全,需要在服务器端进行校验并清除有害的HTML代码,这样才能确保输入到你网站的HTML是安全的。否则,攻击者能够绕过客户端的Javascript验证,并注入不安全的HMTL直接进入您的网站。

jsoup的whitelist清理器能够在服务器端对用户输入的HTML进行过滤,只输出一些安全的标签和属性。

jsoup提供了一系列的Whitelist基本配置,能够满足大多数要求;但如有必要,也可以进行修改,不过要小心。

这个cleaner非常好用不仅可以避免XSS攻击,还可以限制用户可以输入的标签范围。

参见

  • 参阅XSS cheat sheet ,有一个例子可以了解为什么不能使用正则表达式,而采用安全的whitelist parser-based清理器才是正确的选择。
  • 参阅Cleaner ,了解如何返回一个 Document 对象,而不是字符串
  • 参阅Whitelist,了解如何创建一个自定义的whitelist
  • nofollow 链接属性了解

  

转发请注明出处:http://www.cnblogs.com/jycboy/p/jsoupdoc.html

 


如果您觉得阅读本文对您有帮助,请点一下�?推荐”按钮,您的“推荐�?将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利�?
分类: android学习
5
1
« 上一篇: dom4j创建xml
» 下一篇: android Json详解
	</div>
	<div class="postDesc">posted @ <span id="post-date">2015-09-09 11:08</span> <a href="https://www.cnblogs.com/jycboy/">超超boy</a> 阅读(<span id="post_view_count">29614</span>) 评论(<span id="post_comment_count">2</span>)  <a href="https://i.cnblogs.com/EditPosts.aspx?postid=4794049" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(4794049);return false;">收藏</a></div>
</div>
<script type="text/javascript">var allowComments=true,cb_blogId=238784,cb_entryId=4794049,cb_blogApp=currentBlogApp,cb_blogUserGuid='269f3a23-2be8-e411-b908-9dcfd8948a71',cb_entryCreatedDate='2015/9/9 11:08:00';loadViewCount(cb_entryId);var cb_postType=1;var isMarkdown=false;</script>

	<div class="feedbackItem">
		<div class="feedbackListSubtitle">
			<div class="feedbackManage">
				&nbsp;&nbsp;<span class="comment_actions"></span>
			</div>
			<a href="#3896069" class="layer">#1楼</a><a name="3896069" id="comment_anchor_3896069"></a>  <span class="comment_date">2018-01-24 00:47</span> <a id="a_comment_author_3896069" href="https://www.cnblogs.com/lizhenlzlz/" target="_blank">lizhenlzlz</a> <a href="http://msg.cnblogs.com/send/lizhenlzlz" title="发送站内短消息" class="sendMsg2This">&nbsp;</a>
		</div>
		<div class="feedbackCon">
			<div id="comment_body_3896069" class="blog_comment_body">对我有用</div><div class="comment_vote"><a href="javascript:void(0);" class="comment_digg" onclick="return voteComment(3896069,'Digg',this)">支持(0)</a><a href="javascript:void(0);" class="comment_bury" onclick="return voteComment(3896069,'Bury',this)">反对(0)</a></div>
		</div>
	</div>

	<div class="feedbackItem">
		<div class="feedbackListSubtitle">
			<div class="feedbackManage">
				&nbsp;&nbsp;<span class="comment_actions"></span>
			</div>
			<a href="#4098607" class="layer">#2楼</a><a name="4098607" id="comment_anchor_4098607"></a><span id="comment-maxId" style="display:none;">4098607</span><span id="comment-maxDate" style="display:none;">2018/10/25 16:09:57</span>  <span class="comment_date">2018-10-25 16:09</span> <a id="a_comment_author_4098607" href="https://www.cnblogs.com/gomaster/" target="_blank">公子扶摇</a> <a href="http://msg.cnblogs.com/send/%E5%85%AC%E5%AD%90%E6%89%B6%E6%91%87" title="发送站内短消息" class="sendMsg2This">&nbsp;</a>
		</div>
		<div class="feedbackCon">
			<div id="comment_body_4098607" class="blog_comment_body">Let's try GraphQuery, a more powerful HTML/XML parsing language. Project:  <a href="https://github.com/storyicon" target="_blank">https://github.com/storyicon</a></div><div class="comment_vote"><a href="javascript:void(0);" class="comment_digg" onclick="return voteComment(4098607,'Digg',this)">支持(0)</a><a href="javascript:void(0);" class="comment_bury" onclick="return voteComment(4098607,'Bury',this)">反对(0)</a></div><span id="comment_4098607_avatar" style="display:none;">http://pic.cnblogs.com/face/1451775/20181025155548.png</span>
		</div>
	</div>
<div id="comments_pager_bottom"></div></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script>
</div><!--end: forFlow -->
</div><!--end: mainContent 主体内容容器-->

<div id="sideBar">
	<div id="sideBarMain">

公告

昵称: 超超boy
园龄: 3年9个月
粉丝: 75
关注: 20
+加关注
		<div id="blog-calendar" style=""><table id="blogCalendar" class="Cal" cellspacing="0" cellpadding="0" title="Calendar">
<tbody><tr><td colspan="7"><table class="CalTitle" cellspacing="0">
	<tbody><tr><td class="CalNextPrev"><a href="javascript:void(0);" onclick="loadBlogCalendar('2018/12/01');return false;">&lt;</a></td><td align="center">2019年1月</td><td class="CalNextPrev" align="right"><a href="javascript:void(0);" onclick="loadBlogCalendar('2019/02/01');return false;">&gt;</a></td></tr>
</tbody></table></td></tr><tr><th class="CalDayHeader" align="center" abbr="日" scope="col">日</th><th class="CalDayHeader" align="center" abbr="一" scope="col">一</th><th class="CalDayHeader" align="center" abbr="二" scope="col">二</th><th class="CalDayHeader" align="center" abbr="三" scope="col">三</th><th class="CalDayHeader" align="center" abbr="四" scope="col">四</th><th class="CalDayHeader" align="center" abbr="五" scope="col">五</th><th class="CalDayHeader" align="center" abbr="六" scope="col">六</th></tr><tr><td class="CalOtherMonthDay" align="center">30</td><td class="CalOtherMonthDay" align="center">31</td><td align="center">1</td><td align="center">2</td><td align="center">3</td><td align="center">4</td><td class="CalWeekendDay" align="center">5</td></tr><tr><td class="CalWeekendDay" align="center">6</td><td align="center">7</td><td align="center">8</td><td align="center">9</td><td align="center">10</td><td align="center">11</td><td class="CalWeekendDay" align="center">12</td></tr><tr><td class="CalWeekendDay" align="center">13</td><td align="center">14</td><td align="center">15</td><td align="center">16</td><td align="center">17</td><td align="center">18</td><td class="CalWeekendDay" align="center">19</td></tr><tr><td class="CalWeekendDay" align="center">20</td><td align="center">21</td><td align="center">22</td><td class="CalTodayDay" align="center">23</td><td align="center">24</td><td align="center">25</td><td class="CalWeekendDay" align="center">26</td></tr><tr><td class="CalWeekendDay" align="center">27</td><td align="center">28</td><td align="center">29</td><td align="center">30</td><td align="center">31</td><td class="CalOtherMonthDay" align="center">1</td><td class="CalOtherMonthDay" align="center">2</td></tr><tr><td class="CalOtherMonthDay" align="center">3</td><td class="CalOtherMonthDay" align="center">4</td><td class="CalOtherMonthDay" align="center">5</td><td class="CalOtherMonthDay" align="center">6</td><td class="CalOtherMonthDay" align="center">7</td><td class="CalOtherMonthDay" align="center">8</td><td class="CalOtherMonthDay" align="center">9</td></tr>
		<div id="leftcontentcontainer">
			<div id="blog-sidecolumn"><div id="sidebar_search" class="sidebar-block">
    • Android进阶(20)
    • android学习(35)
    • C/C++基础总结(5)
    • GoogleTest单元测试(11)
    • JavaEE(3)
    • java读书笔记(1)
    • java总结(24)
    • kafka(1)
    • Linux学习(5)
    • mysql数据库(7)
    • NoSql数据库(7)
    • SQL Server(1)
    • 笔试面试(5)
    • 操作系统(1)
    • 计算机网络(2)
    • 其他(4)
    • 设计模式(2)
    • 数据结构(1)
    • 数据库原理(2)
    • 算法(7)
    • 杂谈(6)
      • 2018年12月 (2)
      • 2018年4月 (4)
      • 2018年1月 (2)
      • 2017年12月 (1)
      • 2017年11月 (1)
      • 2017年9月 (1)
      • 2017年8月 (1)
      • 2017年4月 (2)
      • 2017年3月 (1)
      • 2017年2月 (10)
      • 2016年12月 (9)
      • 2016年11月 (8)
      • 2016年10月 (3)
      • 2016年9月 (4)
      • 2016年8月 (9)
      • 2016年7月 (7)
      • 2016年6月 (4)
      • 2016年5月 (5)
      • 2016年4月 (10)
      • 2016年3月 (16)
      • 2016年2月 (8)
      • 2016年1月 (6)
      • 2015年12月 (2)
      • 2015年11月 (8)
      • 2015年10月 (3)
      • 2015年9月 (7)
      • 2015年8月 (12)
        • J2EE
        • 	</div><!--end: sideBarMain -->
          </div><!--end: sideBar 侧边栏容器 -->
          <div class="clear"></div>
          </div>回主页"></a>			
          

          超超boy

          </div><!--end: blogTitle 博客的标题和副标题 -->
          <div id="navigator">
          
          		<div id="blog_stats">
          

          随笔 - 146 
          文章 - 0 
          评论 - 80

          	</div><!--end: blogStats -->
          </div><!--end: navigator 博客导航栏 -->
          
              <div id="post_detail">
          

          Jsoup解析Html中文文档

          jsoup 简介
          Java 程序在解析 HTML 文档时,相信大家都接触过 htmlparser 这个开源项目,我曾经在 IBM DW 上发表过两篇关于 htmlparser 的文章,分别是:从 HTML 中攫取你所需的信息和 扩展 HTMLParser 对自定义标签的处理能力。但现在我已经不再使用 htmlparser 了,原因是 htmlparser 很少更新,但最重要的是有了 jsoup 。
          jsoup 是一款 Java 的 HTML 解析器,可直接解析某个 URL 地址、HTML 文本内容。它提供了一套非常省力的 API,可通过 DOM,CSS 以及类似于 jQuery 的操作方法来取出和操作数据。
          jsoup 的主要功能如下:
          1. 从一个 URL,文件或字符串中解析 HTML;
          2. 使用 DOM 或 CSS 选择器来查找、取出数据;
          3. 可操作 HTML 元素、属性、文本;

          官网地址:http://www.open-open.com/jsoup/     

          jsoup Cookbook(中文版)
          入门
          1.解析和遍历一个html文档
          输入
          2.解析一个html字符串
          3.解析一个body片断
          4.根据一个url加载Document对象
          5.根据一个文件加载Document对象
          数据抽取
          6.使用dom方法来遍历一个Document对象
          7.使用选择器语法来查找元素
          8.从元素集合抽取属性、文本和html内容
          9.URL处理
          10.程序示例:获取所有链接
          数据修改
          11.设置属性值
          12.设置元素的html内容
          13.设置元素的文本内容
          html清理
          14.消除不受信任的html (来防止xss攻击)

          1.解析和遍历一个HTML文档
          如何解析一个HTML文档:

          ?
          1
          2
          3
          String html = "<html><head><title>First parse</title></head>"
          + "<body><p>Parsed HTML into a doc.</p></body></html>" ;
          Document doc = Jsoup.parse(html);

            (更详细内容可查看 解析一个HTML字符串.)

          其解析器能够尽最大可能从你提供的HTML文档来创见一个干净的解析结果,无论HTML的格式是否完整。比如它可以处理:

          没有关闭的标签 (比如: <p>Lorem <p>Ipsum parses to <p>Lorem</p> <p>Ipsum</p>)
          隐式标签 (比如. 它可以自动将 <td>Table data</td>包装成<table><tr><td>?)
          创建可靠的文档结构(html标签包含head 和 body,在head只出现恰当的元素)
          一个文档的对象模型
          文档由多个Elements和TextNodes组成 (以及其它辅助nodes:详细可查看:nodes package tree).
          其继承结构如下:Document继承Element继承Node. TextNode继承 Node.
          一个Element包含一个子节点集合,并拥有一个父Element。他们还提供了一个唯一的子元素过滤列表。
          参见
          数据抽取:DOM遍历
          数据抽取:Selector syntax

          2.解析一个HTML字符串
          存在问题
          来自用户输入,一个文件或一个网站的HTML字符串,你可能需要对它进行解析并取其内容,或校验其格式是否完整,或想修改它。怎么办?jsonu能够帮你轻松解决这些问题

          解决方法
          使用静态Jsoup.parse(String html) 方法或 Jsoup.parse(String html, String baseUri)示例代码:

          ?
          1
          2
          3
          String html = "<html><head><title>First parse</title></head>"
          + "<body><p>Parsed HTML into a doc.</p></body></html>" ;
          Document doc = Jsoup.parse(html);

            描述

          parse(String html, String baseUri) 这方法能够将输入的HTML解析为一个新的文档 (Document),参数 baseUri 是用来将相对 URL 转成绝对URL,并指定从哪个网站获取文档。如这个方法不适用,你可以使用 parse(String html) 方法来解析成HTML字符串如上面的示例。.

          只要解析的不是空字符串,就能返回一个结构合理的文档,其中包含(至少) 一个head和一个body元素。

          一旦拥有了一个Document,你就可以使用Document中适当的方法或它父类 Element和Node中的方法来取得相关数据。

           

          3.解析一个body片断

          问题
          假如你有一个HTML片断 (比如. 一个 div 包含一对 p 标签; 一个不完整的HTML文档) 想对它进行解析。这个HTML片断可以是用户提交的一条评论或在一个CMS页面中编辑body部分。

          办法
          使用Jsoup.parseBodyFragment(String html)方法.

          ?
          1
          2
          3
          String html = "<div><p>Lorem ipsum.</p>" ;
          Document doc = Jsoup.parseBodyFragment(html);
          Element body = doc.body();

            说明

          parseBodyFragment 方法创建一个空壳的文档,并插入解析过的HTML到body元素中。假如你使用正常的 Jsoup.parse(String html) 方法,通常你也可以得到相同的结果,但是明确将用户输入作为 body片段处理,以确保用户所提供的任何糟糕的HTML都将被解析成body元素。

          Document.body() 方法能够取得文档body元素的所有子元素,与 doc.getElementsByTag("body")相同。

          保证安全Stay safe
          假如你可以让用户输入HTML内容,那么要小心避免跨站脚本攻击。利用基于 Whitelist 的清除器和 clean(String bodyHtml, Whitelist whitelist)方法来清除用户输入的恶意内容。

          4.从一个URL加载一个Document

          存在问题

          你需要从一个网站获取和解析一个HTML文档,并查找其中的相关数据。你可以使用下面解决方法:

          解决方法

          使用 Jsoup.connect(String url)方法:

          ?
          1
          2
          Document doc = Jsoup.connect( "http://example.com/" ).get();
          String title = doc.title();

            说明

          connect(String url) 方法创建一个新的 Connection, 和 get() 取得和解析一个HTML文件。如果从该URL获取HTML时发生错误,便会抛出 IOException,应适当处理。

          Connection 接口还提供一个方法链来解决特殊请求,具体如下:

          ?
          1
          2
          3
          4
          5
          6
          Document doc = Jsoup.connect( "http://example.com" )
             .data( "query" , "Java" )
             .userAgent( "Mozilla" )
             .cookie( "auth" , "token" )
             .timeout( 3000 )
             .post();

            这个方法只支持Web URLs (httphttps 协议); 假如你需要从一个文件加载,可以使用 parse(File in, String charsetName) 代替。

          5.从一个文件加载一个文档

          问题

          在本机硬盘上有一个HTML文件,需要对它进行解析从中抽取数据或进行修改。

          办法

          可以使用静态 Jsoup.parse(File in, String charsetName, String baseUri) 方法:

          ?
          1
          2
          File input = new File( "/tmp/input.html" );
          Document doc = Jsoup.parse(input, "UTF-8" , "http://example.com/" );

            说明

          parse(File in, String charsetName, String baseUri) 这个方法用来加载和解析一个HTML文件。如在加载文件的时候发生错误,将抛出IOException,应作适当处理。

          baseUri 参数用于解决文件中URLs是相对路径的问题。如果不需要可以传入一个空的字符串。

          另外还有一个方法parse(File in, String charsetName) ,它使用文件的路径做为 baseUri。 这个方法适用于如果被解析文件位于网站的本地文件系统,且相关链接也指向该文件系统。

          6.使用DOM方法来遍历一个文档

          问题

          你有一个HTML文档要从中提取数据,并了解这个HTML文档的结构。

          方法

          将HTML解析成一个Document之后,就可以使用类似于DOM的方法进行操作。示例代码:

          ?
          1
          2
          3
          4
          5
          6
          7
          8
          9
          File input = new File( "/tmp/input.html" );
          Document doc = Jsoup.parse(input, "UTF-8" , "http://example.com/" );
           
          Element content = doc.getElementById( "content" );
          Elements links = content.getElementsByTag( "a" );
          for (Element link : links) {
             String linkHref = link.attr( "href" );
             String linkText = link.text();
          }

            说明

          Elements这个对象提供了一系列类似于DOM的方法来查找元素,抽取并处理其中的数据。具体如下:

          查找元素

          元素数据

          操作HTML和文本

          7.使用选择器语法来查找元素

          问题

          你想使用类似于CSS或jQuery的语法来查找和操作元素。

          方法

          可以使用Element.select(String selector) 和 Elements.select(String selector) 方法实现:

          ?
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          File input = new File( "/tmp/input.html" );
          Document doc = Jsoup.parse(input, "UTF-8" , "http://example.com/" );
           
          Elements links = doc.select( "a[href]" ); //带有href属性的a元素
          Elements pngs = doc.select( "img[src$=.png]" );
             //扩展名为.png的图片
           
          Element masthead = doc.select( "div.masthead" ).first();
             //class等于masthead的div标签
           
          Elements resultLinks = doc.select( "h3.r > a" ); //在h3元素之后的a元素

           说明

          jsoup elements对象支持类似于CSS (或jquery)的选择器语法,来实现非常强大和灵活的查找功能。.

          这个select 方法在DocumentElement,或Elements对象中都可以使用。且是上下文相关的,因此可实现指定元素的过滤,或者链式选择访问。

          Select方法将返回一个Elements集合,并提供一组方法来抽取和处理结果。

          Selector选择器概述

          • tagname: 通过标签查找元素,比如:a
          • ns|tag: 通过标签在命名空间查找元素,比如:可以用 fb|name 语法来查找 <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)]
          • *: 这个符号将匹配所有元素

          Selector选择器组合使用

          • el#id: 元素+ID,比如: div#logo
          • el.class: 元素+class,比如: div.masthead
          • el[attr]: 元素+class,比如: a[href]
          • 任意组合,比如:a[href].highlight
          • ancestor child: 查找某个元素下子元素,比如:可以用.body p 查找在"body"元素下的所有 p元素
          • parent > child: 查找某个父元素下的直接子元素,比如:可以用div.content > p 查找 p 元素,也可以用body > * 查找body标签下所有直接子元素
          • siblingA + siblingB: 查找在A元素之前第一个同级元素B,比如:div.head + div
          • siblingA ~ siblingX: 查找A元素之前的同级X元素,比如:h1 ~ p
          • el, el, el:多个选择器组合,查找匹配任一选择器的唯一元素,例如:div.masthead, div.logo

          伪选择器selectors

          • :lt(n): 查找哪些元素的同级索引值(它的位置在DOM树中是相对于它的父节点)小于n,比如:td:lt(3) 表示小于三列的元素
          • :gt(n):查找哪些元素的同级索引值大于n,比如: div p:gt(2)表示哪些div中有包含2个以上的p元素
          • :eq(n): 查找哪些元素的同级索引值与n相等,比如:form input:eq(1)表示包含一个input标签的Form元素
          • :has(seletor): 查找匹配选择器包含元素的元素,比如:div:has(p)表示哪些div包含了p元素
          • :not(selector): 查找与选择器不匹配的元素,比如: div:not(.logo) 表示不包含 class="logo" 元素的所有 div 列表
          • :contains(text): 查找包含给定文本的元素,搜索不区分大不写,比如: p:contains(jsoup)
          • :containsOwn(text): 查找直接包含给定文本的元素
          • :matches(regex): 查找哪些元素的文本匹配指定的正则表达式,比如:div:matches((?i)login)
          • :matchesOwn(regex): 查找自身包含文本匹配指定正则表达式的元素
          • 注意:上述伪选择器索引是从0开始的,也就是说第一个元素索引值为0,第二个元素index为1等

          可以查看Selector API参考来了解更详细的内容

          8.从元素抽取属性,文本和HTML

          问题

          在解析获得一个Document实例对象,并查找到一些元素之后,你希望取得在这些元素中的数据。

          方法

          示例:

          ?
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>" ;
          Document doc = Jsoup.parse(html); //解析HTML字符串返回一个Document实现
          Element link = doc.select( "a" ).first(); //查找第一个a元素
           
          String text = doc.body().text(); // "An example link"//取得字符串中的文本
          String linkHref = link.attr( "href" ); // "http://example.com/"//取得链接地址
          String linkText = link.text(); // "example""//取得链接地址中的文本
           
          String linkOuterH = link.outerHtml();
               // "<a href="http://example.com"><b>example</b></a>"
          String linkInnerH = link.html(); // "<b>example</b>"//取得链接内的html内容

            说明

          上述方法是元素数据访问的核心办法。此外还其它一些方法可以使用:

          这些访问器方法都有相应的setter方法来更改数据.

          参见

          9.处理URLs

          问题

          你有一个包含相对URLs路径的HTML文档,需要将这些相对路径转换成绝对路径的URLs。

          方法

          1. 在你解析文档时确保有指定base URI,然后
          2. 使用 abs: 属性前缀来取得包含base URI的绝对路径。代码如下: 
            ?
            1
            2
            3
            4
            5
            Document doc = Jsoup.connect( "http://www.open-open.com" ).get();
             
            Element link = doc.select( "a" ).first();
            String relHref = link.attr( "href" ); // == "/"
            String absHref = link.attr( "abs:href" ); // "http://www.open-open.com/"

              说明

          在HTML元素中,URLs经常写成相对于文档位置的相对路径: <a href="/download">...</a>. 当你使用 Node.attr(String key) 方法来取得a元素的href属性时,它将直接返回在HTML源码中指定定的值。

          假如你需要取得一个绝对路径,需要在属性名前加 abs: 前缀。这样就可以返回包含根路径的URL地址attr("abs:href")

          因此,在解析HTML文档时,定义base URI非常重要。

          如果你不想使用abs: 前缀,还有一个方法能够实现同样的功能 Node.absUrl(String key)

          10.示例程序: 获取所有链接

          这个示例程序将展示如何从一个URL获得一个页面。然后提取页面中的所有链接、图片和其它辅助内容。并检查URLs和文本信息。

          运行下面程序需要指定一个URLs作为参数

          ?
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          34
          35
          36
          37
          38
          39
          40
          41
          42
          43
          44
          45
          46
          47
          48
          49
          50
          51
          52
          53
          54
          55
          56
          import org.jsoup.Jsoup;
          import org.jsoup.helper.Validate;
          import org.jsoup.nodes.Document;
          import org.jsoup.nodes.Element;
          import org.jsoup.select.Elements;
           
          import java.io.IOException;
           
          /**
            * Example program to list links from a URL.
            */
          public class ListLinks {
               public static void main(String[] args) throws IOException {
                  // Validate.isTrue(args.length == 1, "usage: supply url to fetch");
                   String url = "http://news.ycombinator.com/" ;
                   print( "Fetching %s..." , url);
           
                   Document doc = Jsoup.connect(url).get();
                   Elements links = doc.select( "a[href]" ); //"a[href]" //带有href属性的a元素
                   Elements media = doc.select( "[src]" );   //利用属性查找元素,比如:[href]
                   Elements imports = doc.select( "link[href]" );
           
                   print( "\nMedia: (%d)" , media.size());
                   for (Element src : media) {
                       if (src.tagName().equals( "img" ))
                           print( " * %s: <%s> %sx%s (%s)" ,
                                   src.tagName(), src.attr( "abs:src" ), src.attr( "width" ), src.attr( "height" ),
                                   trim(src.attr( "alt" ), 20 )); //src.attr("src")结果:<y18.gif> 18x18 () 
                                                              //src.attr("abs:src")结果:<https://news.ycombinator.com/y18.gif> 18x18 ()
                       else
                           print( " * %s: <%s>" , src.tagName(), src.attr( "abs:src" ));
                   }
           
                   print( "\nImports: (%d)" , imports.size());
                   for (Element link : imports) {
                       print( " * %s <%s> (%s)" , link.tagName(),link.attr( "abs:href" ), link.attr( "rel" ));
                   }
           
                   print( "\nLinks: (%d)" , links.size());
                   for (Element link : links) {
                       print( " * a: <%s>  (%s)" , link.attr( "abs:href" ), trim(link.text(), 35 ));
                   }
               }
           
               private static void print(String msg, Object... args) {
                   System.out.println(String.format(msg, args));
               }
           
               private static String trim(String s, int width) {
                   if (s.length() > width)
                       return s.substring( 0 , width- 1 ) + "." ;
                   else
                       return s;
               }
          }
          //org/jsoup/examples/ListLinks.java

            示例输入结果:

          ?
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          34
          35
          36
          37
          38
          39
          40
          41
          42
          43
          44
          45
          46
          47
          48
          Fetching http: //news.ycombinator.com/...
           
          Media: ( 38 )
            * img: <http: //ycombinator.com/images/y18.gif> 18x18 ()
            * img: <http: //ycombinator.com/images/s.gif> 10x1 ()
            * img: <http: //ycombinator.com/images/grayarrow.gif> x ()
            * img: <http: //ycombinator.com/images/s.gif> 0x10 ()
            * script: <http: //www.co2stats.com/propres.php?s=1138>
            * img: <http: //ycombinator.com/images/s.gif> 15x1 ()
            * img: <http: //ycombinator.com/images/hnsearch.png> x ()
            * img: <http: //ycombinator.com/images/s.gif> 25x1 ()
            * img: <http: //mixpanel.com/site_media/images/mixpanel_partner_logo_borderless.gif> x (Analytics by Mixpan.)
            
          Imports: ( 2 )
            * link <http: //ycombinator.com/news.css> (stylesheet)
            * link <http: //ycombinator.com/favicon.ico> (shortcut icon)
            
          Links: ( 141 )
            * a: <http: //ycombinator.com>  ()
            * a: <http: //news.ycombinator.com/news>  (Hacker News)
            * a: <http: //news.ycombinator.com/newest>  (new)
            * a: <http: //news.ycombinator.com/newcomments>  (comments)
            * a: <http: //news.ycombinator.com/leaders>  (leaders)
            * a: <http: //news.ycombinator.com/jobs>  (jobs)
            * a: <http: //news.ycombinator.com/submit>  (submit)
            * a: <http: //news.ycombinator.com/x?fnid=JKhQjfU7gW>  (login)
            * a: <http: //news.ycombinator.com/vote?for=1094578&dir=up&whence=%6e%65%77%73>  ()
            * a: <http: //www.readwriteweb.com/archives/facebook_gets_faster_debuts_homegrown_php_compiler.php?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+readwriteweb+%28ReadWriteWeb%29&utm_content=Twitter>  (Facebook speeds up PHP)
            * a: <http: //news.ycombinator.com/user?id=mcxx>  (mcxx)
            * a: <http: //news.ycombinator.com/item?id=1094578>  (9 comments)
            * a: <http: //news.ycombinator.com/vote?for=1094649&dir=up&whence=%6e%65%77%73>  ()
            * a: <http: //groups.google.com/group/django-developers/msg/a65fbbc8effcd914>  ("Tough. Django produces XHTML.")
            * a: <http: //news.ycombinator.com/user?id=andybak>  (andybak)
            * a: <http: //news.ycombinator.com/item?id=1094649>  (3 comments)
            * a: <http: //news.ycombinator.com/vote?for=1093927&dir=up&whence=%6e%65%77%73>  ()
            * a: <http: //news.ycombinator.com/x?fnid=p2sdPLE7Ce>  (More)
            * a: <http: //news.ycombinator.com/lists>  (Lists)
            * a: <http: //news.ycombinator.com/rss>  (RSS)
            * a: <http: //ycombinator.com/bookmarklet.html>  (Bookmarklet)
            * a: <http: //ycombinator.com/newsguidelines.html>  (Guidelines)
            * a: <http: //ycombinator.com/newsfaq.html>  (FAQ)
            * a: <http: //ycombinator.com/newsnews.html>  (News News)
            * a: <http: //news.ycombinator.com/item?id=363>  (Feature Requests)
            * a: <http: //ycombinator.com>  (Y Combinator)
            * a: <http: //ycombinator.com/w2010.html>  (Apply)
            * a: <http: //ycombinator.com/lib.html>  (Library)
            * a: <http: //www.webmynd.com/html/hackernews.html>  ()
            * a: <http: //mixpanel.com/?from=yc>  ()

            

          11.设置属性的值

          问题

          在你解析一个Document之后可能想修改其中的某些属性值,然后再保存到磁盘或都输出到前台页面。

          方法

          可以使用属性设置方法 Element.attr(String key, String value), 和 Elements.attr(String key, String value).

          假如你需要修改一个元素的 class 属性,可以使用 Element.addClass(String className) 和Element.removeClass(String className) 方法。

          Elements 提供了批量操作元素属性和class的方法,比如:要为div中的每一个a元素都添加一个rel="nofollow" 可以使用如下方法:

          ?
          1
          doc.select( "div.comments a" ).attr( "rel" , "nofollow" );

            说明

          Element中的其它方法一样,attr 方法也是返回当 Element (或在使用选择器是返回 Elements 集合)。这样能够很方便使用方法连用的书写方式。比如:

          ?
          1
          doc.select( "div.masthead" ).attr( "title" , "jsoup" ).addClass( "round-box" );

            

          12.设置一个元素的HTML内容

          问题

          你需要一个元素中的HTML内容

          方法

          可以使用Element中的HTML设置方法具体如下:

          ?
          1
          2
          3
          4
          5
          6
          7
          8
          9
          Element div = doc.select( "div" ).first(); // <div></div>
          div.html( "<p>lorem ipsum</p>" ); // <div><p>lorem ipsum</p></div>
          div.prepend( "<p>First</p>" ); //在div前添加html内容
          div.append( "<p>Last</p>" ); //在div之后添加html内容
          // 添完后的结果: <div><p>First</p><p>lorem ipsum</p><p>Last</p></div>
           
          Element span = doc.select( "span" ).first(); // <span>One</span>
          span.wrap( "<li><a href='http://example.com/'></a></li>" );
          // 添完后的结果: <li><a href="http://example.com"><span>One</span></a></li>

            说明

          参见

          可以查看API参考文档中 Element.prependElement(String tag)Element.appendElement(String tag) 方法来创建新的元素并作为文档的子元素插入其中。

          13.设置元素的文本内容

          问题

          你需要修改一个HTML文档中的文本内容

          方法

          可以使用Element的设置方法::

          ?
          1
          2
          3
          4
          5
          Element div = doc.select( "div" ).first(); // <div></div>
          div.text( "five > four" ); // <div>five > four</div>
          div.prepend( "First " );
          div.append( " Last" );
          // now: <div>First five > four Last</div>

            说明

          文本设置方法与 HTML setter 方法一样:

          对于传入的文本如果含有像 <> 等这样的字符,将以文本处理,而非HTML。

          14.消除不受信任的HTML (来防止XSS攻击)

          问题

          在做网站的时候,经常会提供用户评论的功能。有些不怀好意的用户,会搞一些脚本到评论内容中,而这些脚本可能会破坏整个页面的行为,更严重的是获取一些机要信息,此时需要清理该HTML,以避免跨站脚本cross-site scripting攻击(XSS)。

          方法

          使用jsoup HTML Cleaner 方法进行清除,但需要指定一个可配置的 Whitelist

          ?
          1
          2
          3
          4
          String unsafe =
             "<p><a href='http://example.com/' onclick='stealCookies()'>Link</a></p>" ;
          String safe = Jsoup.clean(unsafe, Whitelist.basic());
          // now: <p><a href="http://example.com/" rel="nofollow">Link</a></p>

            说明

          XSS又叫CSS (Cross Site Script) ,跨站脚本攻击。它指的是恶意攻击者往Web页面里插入恶意html代码,当用户浏览该页之时,嵌入其中Web里面的html代码会被执行,从而达到恶意攻击用户的特殊目的。XSS属于被动式的攻击,因为其被动且不好利用,所以许多人常忽略其危害性。所以我们经常只让用户输入纯文本的内容,但这样用户体验就比较差了。

          一个更好的解决方法就是使用一个富文本编辑器WYSIWYG如CKEditor 和 TinyMCE。这些可以输出HTML并能够让用户可视化编辑。虽然他们可以在客户端进行校验,但是这样还不够安全,需要在服务器端进行校验并清除有害的HTML代码,这样才能确保输入到你网站的HTML是安全的。否则,攻击者能够绕过客户端的Javascript验证,并注入不安全的HMTL直接进入您的网站。

          jsoup的whitelist清理器能够在服务器端对用户输入的HTML进行过滤,只输出一些安全的标签和属性。

          jsoup提供了一系列的Whitelist基本配置,能够满足大多数要求;但如有必要,也可以进行修改,不过要小心。

          这个cleaner非常好用不仅可以避免XSS攻击,还可以限制用户可以输入的标签范围。

          参见

          • 参阅XSS cheat sheet ,有一个例子可以了解为什么不能使用正则表达式,而采用安全的whitelist parser-based清理器才是正确的选择。
          • 参阅Cleaner ,了解如何返回一个 Document 对象,而不是字符串
          • 参阅Whitelist,了解如何创建一个自定义的whitelist
          • nofollow 链接属性了解

            

          转发请注明出处:http://www.cnblogs.com/jycboy/p/jsoupdoc.html

           


          如果您觉得阅读本文对您有帮助,请点一下�?推荐”按钮,您的“推荐�?将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利�?
          分类: android学习
          5
          1
          « 上一篇: dom4j创建xml
          » 下一篇: android Json详解
          	</div>
          	<div class="postDesc">posted @ <span id="post-date">2015-09-09 11:08</span> <a href="https://www.cnblogs.com/jycboy/">超超boy</a> 阅读(<span id="post_view_count">29614</span>) 评论(<span id="post_comment_count">2</span>)  <a href="https://i.cnblogs.com/EditPosts.aspx?postid=4794049" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(4794049);return false;">收藏</a></div>
          </div>
          <script type="text/javascript">var allowComments=true,cb_blogId=238784,cb_entryId=4794049,cb_blogApp=currentBlogApp,cb_blogUserGuid='269f3a23-2be8-e411-b908-9dcfd8948a71',cb_entryCreatedDate='2015/9/9 11:08:00';loadViewCount(cb_entryId);var cb_postType=1;var isMarkdown=false;</script>
          

          	<div class="feedbackItem">
          		<div class="feedbackListSubtitle">
          			<div class="feedbackManage">
          				&nbsp;&nbsp;<span class="comment_actions"></span>
          			</div>
          			<a href="#3896069" class="layer">#1楼</a><a name="3896069" id="comment_anchor_3896069"></a>  <span class="comment_date">2018-01-24 00:47</span> <a id="a_comment_author_3896069" href="https://www.cnblogs.com/lizhenlzlz/" target="_blank">lizhenlzlz</a> <a href="http://msg.cnblogs.com/send/lizhenlzlz" title="发送站内短消息" class="sendMsg2This">&nbsp;</a>
          		</div>
          		<div class="feedbackCon">
          			<div id="comment_body_3896069" class="blog_comment_body">对我有用</div><div class="comment_vote"><a href="javascript:void(0);" class="comment_digg" onclick="return voteComment(3896069,'Digg',this)">支持(0)</a><a href="javascript:void(0);" class="comment_bury" onclick="return voteComment(3896069,'Bury',this)">反对(0)</a></div>
          		</div>
          	</div>
          
          	<div class="feedbackItem">
          		<div class="feedbackListSubtitle">
          			<div class="feedbackManage">
          				&nbsp;&nbsp;<span class="comment_actions"></span>
          			</div>
          			<a href="#4098607" class="layer">#2楼</a><a name="4098607" id="comment_anchor_4098607"></a><span id="comment-maxId" style="display:none;">4098607</span><span id="comment-maxDate" style="display:none;">2018/10/25 16:09:57</span>  <span class="comment_date">2018-10-25 16:09</span> <a id="a_comment_author_4098607" href="https://www.cnblogs.com/gomaster/" target="_blank">公子扶摇</a> <a href="http://msg.cnblogs.com/send/%E5%85%AC%E5%AD%90%E6%89%B6%E6%91%87" title="发送站内短消息" class="sendMsg2This">&nbsp;</a>
          		</div>
          		<div class="feedbackCon">
          			<div id="comment_body_4098607" class="blog_comment_body">Let's try GraphQuery, a more powerful HTML/XML parsing language. Project:  <a href="https://github.com/storyicon" target="_blank">https://github.com/storyicon</a></div><div class="comment_vote"><a href="javascript:void(0);" class="comment_digg" onclick="return voteComment(4098607,'Digg',this)">支持(0)</a><a href="javascript:void(0);" class="comment_bury" onclick="return voteComment(4098607,'Bury',this)">反对(0)</a></div><span id="comment_4098607_avatar" style="display:none;">http://pic.cnblogs.com/face/1451775/20181025155548.png</span>
          		</div>
          	</div>
          <div id="comments_pager_bottom"></div></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script>
          
          </div><!--end: forFlow -->
          </div><!--end: mainContent 主体内容容器-->
          
          <div id="sideBar">
          	<div id="sideBarMain">
          

          公告

          昵称: 超超boy
          园龄: 3年9个月
          粉丝: 75
          关注: 20
          +加关注
          		<div id="blog-calendar" style=""><table id="blogCalendar" class="Cal" cellspacing="0" cellpadding="0" title="Calendar">
          <tbody><tr><td colspan="7"><table class="CalTitle" cellspacing="0">
          	<tbody><tr><td class="CalNextPrev"><a href="javascript:void(0);" onclick="loadBlogCalendar('2018/12/01');return false;">&lt;</a></td><td align="center">2019年1月</td><td class="CalNextPrev" align="right"><a href="javascript:void(0);" onclick="loadBlogCalendar('2019/02/01');return false;">&gt;</a></td></tr>
          </tbody></table></td></tr><tr><th class="CalDayHeader" align="center" abbr="日" scope="col">日</th><th class="CalDayHeader" align="center" abbr="一" scope="col">一</th><th class="CalDayHeader" align="center" abbr="二" scope="col">二</th><th class="CalDayHeader" align="center" abbr="三" scope="col">三</th><th class="CalDayHeader" align="center" abbr="四" scope="col">四</th><th class="CalDayHeader" align="center" abbr="五" scope="col">五</th><th class="CalDayHeader" align="center" abbr="六" scope="col">六</th></tr><tr><td class="CalOtherMonthDay" align="center">30</td><td class="CalOtherMonthDay" align="center">31</td><td align="center">1</td><td align="center">2</td><td align="center">3</td><td align="center">4</td><td class="CalWeekendDay" align="center">5</td></tr><tr><td class="CalWeekendDay" align="center">6</td><td align="center">7</td><td align="center">8</td><td align="center">9</td><td align="center">10</td><td align="center">11</td><td class="CalWeekendDay" align="center">12</td></tr><tr><td class="CalWeekendDay" align="center">13</td><td align="center">14</td><td align="center">15</td><td align="center">16</td><td align="center">17</td><td align="center">18</td><td class="CalWeekendDay" align="center">19</td></tr><tr><td class="CalWeekendDay" align="center">20</td><td align="center">21</td><td align="center">22</td><td class="CalTodayDay" align="center">23</td><td align="center">24</td><td align="center">25</td><td class="CalWeekendDay" align="center">26</td></tr><tr><td class="CalWeekendDay" align="center">27</td><td align="center">28</td><td align="center">29</td><td align="center">30</td><td align="center">31</td><td class="CalOtherMonthDay" align="center">1</td><td class="CalOtherMonthDay" align="center">2</td></tr><tr><td class="CalOtherMonthDay" align="center">3</td><td class="CalOtherMonthDay" align="center">4</td><td class="CalOtherMonthDay" align="center">5</td><td class="CalOtherMonthDay" align="center">6</td><td class="CalOtherMonthDay" align="center">7</td><td class="CalOtherMonthDay" align="center">8</td><td class="CalOtherMonthDay" align="center">9</td></tr>
          
          		<div id="leftcontentcontainer">
          			<div id="blog-sidecolumn"><div id="sidebar_search" class="sidebar-block">
          
          • Android进阶(20)
          • android学习(35)
          • C/C++基础总结(5)
          • GoogleTest单元测试(11)
          • JavaEE(3)
          • java读书笔记(1)
          • java总结(24)
          • kafka(1)
          • Linux学习(5)
          • mysql数据库(7)
          • NoSql数据库(7)
          • SQL Server(1)
          • 笔试面试(5)
          • 操作系统(1)
          • 计算机网络(2)
          • 其他(4)
          • 设计模式(2)
          • 数据结构(1)
          • 数据库原理(2)
          • 算法(7)
          • 杂谈(6)
            • 2018年12月 (2)
            • 2018年4月 (4)
            • 2018年1月 (2)
            • 2017年12月 (1)
            • 2017年11月 (1)
            • 2017年9月 (1)
            • 2017年8月 (1)
            • 2017年4月 (2)
            • 2017年3月 (1)
            • 2017年2月 (10)
            • 2016年12月 (9)
            • 2016年11月 (8)
            • 2016年10月 (3)
            • 2016年9月 (4)
            • 2016年8月 (9)
            • 2016年7月 (7)
            • 2016年6月 (4)
            • 2016年5月 (5)
            • 2016年4月 (10)
            • 2016年3月 (16)
            • 2016年2月 (8)
            • 2016年1月 (6)
            • 2015年12月 (2)
            • 2015年11月 (8)
            • 2015年10月 (3)
            • 2015年9月 (7)
            • 2015年8月 (12)
              • J2EE
              • 	</div><!--end: sideBarMain -->
                </div><!--end: sideBar 侧边栏容器 -->
                <div class="clear"></div>
                </div><!--end: main -->
                <div class="clear"></div>
                <div id="footer">
                

                Copyright ©2019 超超boy

              • 0
                点赞
              • 1
                收藏
                觉得还不错? 一键收藏
              • 0
                评论
              YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明

              “相关推荐”对你有帮助么?

              • 非常没帮助
              • 没帮助
              • 一般
              • 有帮助
              • 非常有帮助
              提交
              评论
              添加红包

              请填写红包祝福语或标题

              红包个数最小为10个

              红包金额最低5元

              当前余额3.43前往充值 >
              需支付:10.00
              成就一亿技术人!
              领取后你会自动成为博主和红包主的粉丝 规则
              hope_wisdom
              发出的红包
              实付
              使用余额支付
              点击重新获取
              扫码支付
              钱包余额 0

              抵扣说明:

              1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
              2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

              余额充值