java利用htmlparser獲取html中想要的代碼具體實現(xiàn)
這兩天需要做一些東西,需要抓取別人網(wǎng)頁中的一些信息。最后用htmlparser來解析html。
直接從代碼中看吧:
首先需要注意導(dǎo)入包為:import org.htmlparser下面的包
List<Mp3> mp3List = new ArrayList<Mp3>();
try{
Parser parser = new Parser(htmlStr);//初始化Parser,這里要注意導(dǎo)入包為org.htmlparser。這里參數(shù)有很多。這個地方我寫的是提前獲取好的html文本。也可以傳入URl對象
parser.setEncoding("utf-8");//設(shè)置編碼機
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轉(zhuǎn)換為TagNode才能獲取某一個標(biāo)簽的屬性
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': '黃渤
則是從網(wǎng)頁中解析到的內(nèi)容。
相關(guān)文章
java實現(xiàn)excel和txt文件互轉(zhuǎn)
本篇文章主要介紹了java實現(xiàn)excel和txt文件互轉(zhuǎn)的相關(guān)知識。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04SpringBoot項目在啟動后自動關(guān)閉的實現(xiàn)
我們在寫spring?boot?web項目時,有時會遇到啟動后立即關(guān)閉的情況,?本文主要介紹了SpringBoot項目在啟動后自動關(guān)閉的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-01-01