It looked like nice solution for my task, so I started to implement simple application to parse information from my own blog.
It was quite easy. Parsing in HTML Parser library can be applied in several simple steps.
The primary class of this library is Parser one. Parser can be created via constructors that take String, URL or Lexer (utility class from the HTML parser library).
// Here we create instance of parser
Parser parser = new Parser ("http://example.com");
NodeList list = parser.parse (null);
// here we obtain list of nodes from the page
If user wants to filter posts by tag name, attribute name or attribute value, he should apply the second principle instance of HTML parser library - Filter. User can combine different filters in accordance to required data to parse. Here you can observe documentation for it.
// elements() gets all elements form the page
NodeIterator ni = parser.elements();
// here we set combined filter by tag name
// and attribute name
NodeFilter nodeFilter =
new AndFilter (
new TagNameFilter ("Some tag name here"),
new HasChildFilter (
new HasAttributeFilter("border","0")
)
);
// and via collectInfo() method we collect info to instance of nodeList
for (NodeIterator nodeIterator = parser.elements(); nodeIterator.hasMoreNodes(); ) {
nodeIterator.nextNode().collectInto(nodeList, nodeFilter);
}
Talking about filters we should put our attention on official documentation of filters package.
So user can find some information on html page selected write node and collect required information to his program. It's important to say that HTML parser library has much more features then I described. Here you've read simple example about parsing HTML in Java.
Немає коментарів:
Дописати коментар