這兩天需要做一些東西,需要抓取別人網頁中的一些信息。最后用htmlparser來解析html。
直接從代碼中看吧:
首先需要注意導入包為:import org.htmlparser下面的包
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("http://?")==-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': '黃渤
則是從網頁中解析到的內容。
新聞熱點
疑難解答