[持续更新]htmlParser----Java处理html的利器

1.获取所有某种tag的元素

Parser parser = new Parser();
parser.setURL(path);
//parser.setInputHTML(node.toHtml());
parser.setEncoding("UTF-8");
//获取某种tag的元素
NodeFilter filter = new TagNameFilter("A");
NodeList nodes=parser.extractAllNodesThatMatch(filter);
//创建HtmlPage,获取相关元素
HtmlPage page= new HtmlPage(parser);
parser.visitAllNodesWith(page);
NodeList list = page.getBody();

2.Node常用的操作

String s = certainNode.toPlainTextString()//获取node的纯文本内容(不包括tag)
NodeList nl = certainNode.getChildren();//获取子节点
Node n = certainNode.getParent();//获取父节点
Node n = certainNode.getPreviousSibling();//获取上一个兄弟节点
Node n = certainNode.getNextSibling();//获取下一个兄弟节点
String s = certainNode.toHtml()//获取node的html内容(包括tag)
boolean b = certainNode instanceof LinkTag;//是否是某一类型的tag,LinkTag是内置的,在org.htmlparser.tags下

3.NodeList常用的操作

int size = certainNodeList.size();
Node n = certainNodeList.elementAt(int i);//获取某一元素

4.遍历NodeList

SimpleNodeIterator iterator = nodeList.elements();
while(iterator.hasMoreNodes()){
    Nodenode =iterator.nextNode();
    ...
}

5.判断某一节点类型的方法

1)node.getClass().toString().equals("class org.htmlparser.nodes.TextNode");
2)node.toHtml().trim().toLowerCase().startsWith("<ul");
3)node instanceof HeadingTag;





附录:

htmlparser的tag:

reference:http://htmlparser.sourceforge.net/javadoc/org/htmlparser/tags/package-summary.html

AppletTag

AppletTag represents an <Applet> tag.

BaseHrefTag

BaseHrefTag represents an <Base> tag.

BodyTag

A Body Tag.

Bullet

A bullet tag.

BulletList

A bullet list tag.

CompositeTag

The base class for tags that have an end tag.

DefinitionList

A definition list tag (dl).

DefinitionListBullet

A definition list bullet tag (either DD or DT).

Div

A div tag.

DoctypeTag

The HTML Document Declaration Tag can identify <!DOCTYPE> tags.

FormTag

Represents a FORM tag.

FrameSetTag

Identifies an frame set tag.

FrameTag

Identifies a frame tag

HeadingTag

A heading (h1 - h6) tag.

HeadTag

A head tag.

Html

A html tag.

ImageTag

Identifies an image tag.

InputTag

An input tag in a form.

JspTag

The JSP/ASP tags like <%...%> can be identified by this class.

LabelTag

A label tag.

LinkTag

Identifies a link tag.

MetaTag

A Meta Tag

ObjectTag

ObjectTag represents an <Object> tag.

OptionTag

An option tag within a form.

ParagraphTag

A paragraph (p) tag.

ProcessingInstructionTag

The XML processing instructions like <?xml ...

ScriptTag

A script tag.

SelectTag

A select tag within a form.

Span

A span tag.

StyleTag

A StyleTag represents a <style> tag.

TableColumn

A table column tag.

TableHeader

A table header tag.

TableRow

A table row tag.

TableTag

A table tag.

TextareaTag

A text area tag within a form.

TitleTag

A title tag.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值