一下代码是获取sina首页的内容
package com;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
public class Html {
public static void main(String []args){
try{
Parser parser = new Parser("http://www.sina.com.cn");
parser.setEncoding("gb2312");
NodeList list = parser.parse(null);
System.out.println(list.toHtml());
}catch(Exception e){
e.printStackTrace();
}
}
}
下面的实例是获取sina首页上的图片地址,先查询“img”标签,然后利用ImageTag获取src属性
package com;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeList;
public class ImageSrc {
public static void main(String []args){
try{
Parser parser = new Parser("http://www.sina.com.cn");
parser.setEncoding("gb2312");
NodeFilter nodeFilter = new TagNameFilter("img");
NodeList nodeList = parser.extractAllNodesThatMatch(nodeFilter);
Node node = null;
ImageTag imageTag = null;
if(nodeList != null){
for(int i=0;i<nodeList.size();i++){
node = (Node)nodeList.elementAt(i);
if(node instanceof ImageTag){
imageTag = (ImageTag)node;
System.out.println(imageTag.getAttribute("src"));
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}