Jsoup使用教程

一、解析和遍历一个HTML文档
1、解析Html及Url链接

1 String html = "<html><head><title>First parse</title></head>"
2   + "<body><p>Parsed HTML into a doc.</p></body></html>";
3 Document doc = Jsoup.parse(html);//解析html文档
1 Document doc = Jsoup.connect("http://example.com/").get();//解析Url链接地址
2 String title = doc.title();

2、解析body片段

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

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

3、使用Dom获取元素

查找元素

4、从元素抽取属性,文本和HTML

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

 二、与百度链接在一起

如何设置百度搜索结果显示更多条数
【必备参数】:

  wd——查询的关键词(Keyword)

  pn——显示结果的页数(Page Number)

  cl——搜索类型(Class),cl=3为网页搜索

  【可选参数】:

  rn——搜索结果显示条数(Record Number),取值范围在10--100条之间,缺省设置rn=10

原文地址:https://www.cnblogs.com/wang3680/p/3252626.html