Jsoup学习笔记2:Jsoup解析HTML代码标签与属性

来源:互联网 发布:网络共享文件夹 编辑:程序博客网 时间:2024/05/16 13:42

转载自:http://jilongliang.iteye.com/blog/1922295?utm_source=tuicool

接着上一篇的Jsoup学习笔记1继续学习,虽然是转载自上面链接的文章,但是程序做了一点改动,方便自己以后的查看

package com.daxiang.myjsoup;import org.jsoup.Jsoup;  import org.jsoup.nodes.Document;  import org.jsoup.nodes.Element;  import org.jsoup.select.Elements;    public class Jsoup1 {      public static void main(String[] args) {          StringBuffer buffer=new StringBuffer("<table border=\"1\" align=\"center\">");          buffer.append("<tr><td colspan=\"2\" class='td'>电&nbsp;&nbsp;话:</td><td id=\"tel\"></td></tr>");          buffer.append("<tr><td colspan=\"2\" class='td'>用&nbsp;&nbsp;户:</td><td id=\"username\"></td></tr>");          buffer.append("<tr><td colspan=\"2\" class='td'><img src=\"images/1.png\"/></td></tr>");          buffer.append("</table>");          String html=buffer.toString();          Document doc=Jsoup.parse(html, "GBK");          Elements table=doc.select("table");//选择table标签          for(Element tab:table){              tab.attr("border", "2");//修改table的边框值          }           Element td_classfirst = doc.select("td.td").first();            td_classfirst.remove();//把第一个td的class=td的样式的标签都移除                Elements pngs = doc.select("img[src$=.png]");// 所有引用 png 图片的元素           for(Element png:pngs){               String pngText=png.text();               String src=png.attr("src");//根据属性名获取src的路径               System.out.println(src+pngText);           }                    Element td_classlast = doc.select("td.td").last();            td_classlast.remove();//把第最后的一个td的class=td的样式的标签都移除                    //在id为tel的td标签里面添加一个value等于121212121的值 如:<td id="tel" value="121212121"></td>           doc.getElementById("tel").val("121212121");//           //在id为tel的td标签添加一个文本值 如:<td id="tel">121212121</td>           doc.getElementById("tel").html("121212121");//                      String newHtml=doc.toString();           System.out.println(newHtml);      }  }  
程序执行结果如下:

images/1.png<html> <head></head> <body>  <table border="2" align="center">   <tbody>    <tr>     <td id="tel" value="121212121">121212121</td>    </tr>    <tr>     <td colspan="2" class="td">用  户:</td>     <td id="username"></td>    </tr>    <tr></tr>   </tbody>  </table> </body></html>



0 0
原创粉丝点击