java利用htmlparser获取html中想要的代码具体实现

2022-10-20,,,,

这两天需要做一些东西,需要抓取别人网页中的一些信息。最后用htmlparser来解析html。

直接从代码中看吧:

首先需要注意导入包为:import org.htmlparser下面的包

复制代码 代码如下:
list<mp3> mp3list = new arraylist<mp3>();
        try{
            parser parser = new parser(htmlstr);//初始化parser,这里要注意导入包为org.htmlparser。这里参数有很多。这个地方我写的是提前获取好的html文本。也可以传入url对象
            parser.setencoding("utf-8");//设置编码机
            andfilter filter =
                new andfilter(
                              new tagnamefilter("div"),
                             new hasattributefilter("id","songlistwrapper")
              );//通过filter找到div且div的id为songlistwrapper

              nodelist nodes = parser.parse(filter);//通过filter获取nodes
              node node = nodes.elementat(0);
              nodelist nodeschild = node.getchildren();
              node[] nodesarr = nodeschild.tonodearray();
              nodelist nodeschild2 = nodesarr[1].getchildren();
              node[] nodesarr2 = nodeschild2.tonodearray();
              node nodeul = nodesarr2[1];
              node[] nodesli = nodeul.getchildren().tonodearray();//解析出nodesli为想要

           
              for(int i=2;i<nodesli.length;i++){
                  //system.out.println(nodesli[i].tohtml());
                  node tempnode =  nodesli[i];
                  tagnode tagnode = new tagnode();//通过tagnode获得属性,只有将node转换为tagnode才能获取某一个标签的属性
                  tagnode.settext(tempnode.tohtml());
                  string clastr = tagnode.getattribute("class");//clastr为bb-dotimg clearfix  song-item-hook { 'songitem': { 'sid': '113275822', 'sname': '我的要求不算高', 'author': '黄渤' } }
                  clastr = clastr.replaceall(" ", "");
                  if(clastr.indexof("\\?")==-1){
                      pattern pattern = pattern.compile("[\\s\\wa-z\\-]+\\{'songitem':\\{'sid':'([\\d]+)','sname':'([\\s\\s]*)','author':'([\\s\\s]*)'\\}\\}");
                      matcher matcher = pattern.matcher(clastr);
                      if(matcher.find()){
                          mp3 mp3 = new mp3();
                          mp3.setsid(matcher.group(1));
                          mp3.setsname(matcher.group(2));
                          mp3.setauthor(matcher.group(3));
                          mp3list.add(mp3);
                          //for(int j=1;j<=matcher.groupcount();j++){
                              //system.out.print("   "+j+"--->"+matcher.group(j));
                          //}
                      }
                  }
                  //system.out.println(matcher.find());
              }

            }catch(exception e){
                e.printstacktrace();
            }

以上是我在项目中解析的东西,使用还是比较简单的,容易上手。
              ////clastr为bb-dotimg clearfix  song-item-hook { 'songitem': { 'sid': '113275822', 'sname': '我的要求不算高', 'author': '黄渤

则是从网页中解析到的内容。

《java利用htmlparser获取html中想要的代码具体实现.doc》

下载本文的Word格式文档,以方便收藏与打印。