---
title: "Java解析HTML"
author: "longware"
date: "2010-11-29T22:54:06Z"
tags: []
categories: ["编程语言"]
slug: "java-html"
draft: false
lastmod: "2010-11-29T22:54:06Z"
id: 828723
url: "https://longware.iteye.com/blog/828723"
---

看了下，有很多parser，没有一个个看，下了个http://sourceforge.net/projects/htmlparser/files/

节点解析是用遍历方式的，或者遍历时加个filter


```java

	public static void printNode(NodeList nodelist) {
		for (int i = 0; nodelist != null && i < nodelist.size(); i++) {
			Node node = nodelist.elementAt(i);
			System.out.print(node.getText());
			
			printNode(node.getChildren());
		}
	}

	public static void main(String[] args) {
		try {
			Parser parser = new Parser(url);
			NodeList nodelist = parser.parse(null);
			//printNode(nodelist);
			
			NodeFilter filter = new TagNameFilter("tr");
			NodeList list = nodelist.extractAllNodesThatMatch(filter, true);
			printNode(list);

		} catch (ParserException e) {
			e.printStackTrace();
		}

	}

```


加入html中有


```java

...
<div id=xxx>
...
</div>
...

```


在js中，有getElementById(xxx)马上就能找到此div，但是java里貌似没有此现成的方法，难不成要一个个遍历，然后加if--then--else，那太累了。

http://www.open-open.com/30.htm 里面还有其他的parser，没一个个看

大家说说你们经历。