java-jsoup解析html页面的内容

来源:互联网 发布:神魔诛天变身进阶数据 编辑:程序博客网 时间:2024/05/24 15:38

分类: java 2147人阅读 评论(0) 收藏 举报
jsoup


前面一篇文章讲述了 怎么用httpclient发送页面请求,下面要做的就是 爬取请求到的页面的 内容了。 jsoup可以帮助我们很好的解析页面内容。具体例子我们在上文的框架里做示范。

上文链接:http://blog.csdn.net/zzq900503/article/details/10006751 


jsoup的介绍:http://baike.baidu.com/view/4066913.htm

jsoup api:http://jsoup.org/apidocs/

jsoup 教程:http://www.open-open.com/jsoup/


增加两个import 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import org.jsoup.safety.Whitelist;  
  2. import org.jsoup.select.Elements;  



现在我要抓取我的博客首页的部分内容:


主要是修改main函数里的内容 其他部分没做更改

main函数内容更改如下:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static void main(String[] args) {  
  2.       
  3.       
  4.     String url ="http://blog.csdn.net/zzq900503";  
  5.       
  6.     initHttpClient();  
  7.       
  8.     String content =crawlPageContent(httpClient,url);  
  9. //  System.out.println(content);  
  10.     Document doc = Jsoup.parse(content);  
  11.     String title = doc.title();  
  12.     System.out.println(title);  
  13.       
  14.     Element a=doc.getElementById("panel_Profile");  
  15.       
  16.     Elements li_content=a.getElementsByTag("li");  
  17.   
  18.     //提取方式一:  
  19. //  for(Element i:li_content)  
  20. //  {  
  21. //      String tag=i.tagName();  
  22. //      if(tag.equals("li"))  
  23. //      {  
  24. //          System.out.println(i.text());  
  25. //            
  26. //      }  
  27. //        
  28. //        
  29. //  }  
  30.       
  31.     //提取方式二:  
  32. //  for(Element i:li_content)  
  33. //  {  
  34. //      String tag=i.tagName();  
  35. //      if(tag.equals("li"))  
  36. //      {  
  37. //          String fre_content= i.ownText();  
  38. //        
  39. //         System.out.println(fre_content);  
  40. //         if(i.children().size()>0&&i.children()!=null)  
  41. //         {  
  42. //         String after_content=i.child(0).text();  
  43. //         System.out.println(after_content);  
  44. //         }  
  45. //      }  
  46. //        
  47. //        
  48. //  }  
  49.       
  50.       
  51.     //提取方式三:  
  52.     for(Element i:li_content)  
  53.     {  
  54.         String tag=i.tagName();  
  55.         if(tag.equals("li"))  
  56.         {  
  57.             String all_content=i.text();  
  58.             String all_string=Jsoup.clean(all_content, Whitelist.none());  
  59.         String[] all=all_string.split(":");        
  60.            if(all.length>0&&all!=null)  
  61.            {  
  62.                String fre_content=all[0].toString();  
  63.                System.out.println(fre_content);  
  64.            String after_content=all[1].toString();  
  65.            System.out.println(after_content);  
  66.            }  
  67.         }  
  68.           
  69.           
  70.     }  
  71.       
  72.       
  73.       
  74. }  


得到的结果如下:

方式一:



方式二:



方式三:




除了上述的用httpclient获取页面内容外,jsoup本身也支持 字符串,链接,文档文件的解析。(只需要在工程中引用jsoup-1.3.3.jar即可)例子如下:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public void parseString() {    
  2.     String html = "<html><head><title>blog</title></head><body onload='test()'><p>Parsed HTML into a doc.</p></body></html>";    
  3.     Document doc = Jsoup.parse(html);    
  4.     System.out.println(doc);    
  5.     Elements es = doc.body().getAllElements();    
  6.     System.out.println(es.attr("onload"));    
  7.     System.out.println(es.select("p"));    
  8. }    
  9.   
  10. public void parseUrl() {    
  11.     try {    
  12.         Document doc = Jsoup.connect("http://www.baidu.com/").get();    
  13.         Elements hrefs = doc.select("a[href]");    
  14.         System.out.println(hrefs);    
  15.         System.out.println("------------------");    
  16.         System.out.println(hrefs.select("[href^=http]"));    
  17.     } catch (IOException e) {    
  18.         e.printStackTrace();    
  19.     }    
  20. }    
  21.   
  22. public void parseFile() {    
  23.     try {    
  24.         File input = new File("input.html");    
  25.         Document doc = Jsoup.parse(input, "UTF-8");    
  26.         // 提取出所有的编号    
  27.         Elements codes = doc.body().select("td[title^=IA] > a[href^=javascript:view]");    
  28.         System.out.println(codes);    
  29.         System.out.println("------------------");    
  30.         System.out.println(codes.html());    
  31.     } catch (IOException e) {    
  32.         e.printStackTrace();    
  33.     }    
  34. }    





jsoup解析有很多种方法能得到同样的结构,就看你想用哪种思路。

有用id定位的  有用tagname获取的 有用class 获取的  




常用的方法如下:

jsoup提供类似JS获取html元素:
getElementById(String id) 用id获得元素
getElementsByTag(String tag) 用标签获得元素
getElementsByClass(String className) 用class获得元素
getElementsByAttribute(String key)  用属性获得元素
同时还提供下面的方法提供获取兄弟节点:siblingElements(), firstElementSibling(), lastElementSibling();nextElementSibling(), previousElementSibling()


获得与设置元素的数据
attr(String key)  获得元素的数据 attr(String key, String value) 设置元素数据 
attributes() 获得所以属性
id(), className()  classNames() 获得id class得值
text()获得文本值
text(String value) 设置文本值
html() 获取html 
html(String value)设置html
outerHtml() 获得内部html
data()获得数据内容
tag()  获得tag 和 tagName() 获得tagname 


操作html元素:
append(String html), prepend(String html)
appendText(String text), prependText(String text)
appendElement(String tagName), prependElement(String tagName)
html(String value)


jsoup还提供了类似于JQuery方式的选择器
采用选择器来检索数据
tagname 使用标签名来定位,例如 a 
ns|tag     使用命名空间的标签定位,例如 fb:name 来查找 <fb:name> 元素 
#id     使用元素 id 定位,例如 #logo 
.class     使用元素的 class 属性定位,例如 .head 
*     定位所有元素 
[attribute] 使用元素的属性进行定位,例如 [href] 表示检索具有 href 属性的所有元素 
[^attr] 使用元素的属性名前缀进行定位,例如 [^data-] 用来查找 HTML5 的 dataset 属性 
[attr=value]使用属性值进行定位,例如 [width=500] 定位所有 width 属性值为 500 的元素 
[attr^=value],[attr$=value],[attr*=value] 这三个语法分别代表,属性以 value 开头、结尾以及包含 
[attr~=regex]使用正则表达式进行属性值的过滤,例如 img[src~=(?i)\.(png|jpe?g)] 
以上是最基本的选择器语法,这些语法也可以组合起来使用


组合用法
el#id      定位id值某个元素,例如 a#logo -> <a id=logo href= … > 
el.class 定位 class 为指定值的元素,例如 div.head -> <div class=head>xxxx</div> 
el[attr] 定位所有定义了某属性的元素,例如 a[href] 
以上三个任意组合     例如 a[href]#logo 、a[name].outerlink 


除了一些基本的语法以及这些语法进行组合外,jsoup 还支持使用表达式进行元素过滤选择
:lt(n)     例如 td:lt(3) 表示小于三列 
:gt(n)     div p:gt(2) 表示 div 中包含 2 个以上的 p 
:eq(n)     form input:eq(1) 表示只包含一个 input 的表单 
:has(seletor)     div:has(p) 表示包含了 p 元素的 div 
:not(selector)     div:not(.logo) 表示不包含 class=logo 元素的所有 div 列表 
:contains(text)     包含某文本的元素,不区分大小写,例如 p:contains(oschina) 
:containsOwn(text)     文本信息完全等于指定条件的过滤 
:matches(regex)     使用正则表达式进行文本过滤:div:matches((?i)login) 
:matchesOwn(regex)     使用正则表达式找到自身的文本 




http://blog.csdn.net/zzq900503/article/details/10071307

0 0
原创粉丝点击