日期:2014-05-18 浏览次数:20952 次
1. import java.util.HashMap;
2. import java.util.Map;
3. import org.htmlparser.Node;
4. import org.htmlparser.NodeFilter;
5. import org.htmlparser.Parser;
6. import org.htmlparser.tags.LinkTag;
7. import org.htmlparser.util.NodeList;
8. import com.yao.http.HttpRequester;
9. import com.yao.http.HttpRespons;
10.
11. /**
12. * JAVA中使用Htmlparse解析HTML文档,使用htmlparse遍历出HTML文档的所有超链接(<a>标记)。
13. *
14. * @author YYmmiinngg
15. */
16. public class Test {
17. public static void main(String[] args) {
18. try {
19. /* 首先我们先使用HttpRequester类和HttpRespons类获得一个HTTP请求中的数据(HTML文档)。 可以从 (http://download.csdn.net/source/321516)中下载htmlloader,该库中有上述类;或从我的《JAVA发送HTTP请求,返回HTTP响应内容,实例及应用》一文中摘取上述两JAVA类的代码。htmlparse可以从(http://download.csdn.net/source/321507)中下载
20. */
21. Map<String, String> map = new HashMap<String, String>();
22. HttpRequester request = new HttpRequester();
23. HttpRespons hr = request.sendGet("http://www.baidu.com");
24.
25. Parser parser = Parser.createParser(hr.getContent(), hr
26. .getContentEncoding());
27. try {
28. // 通过过滤器过滤出<A>标签
29. NodeList nodeList = parser
30. .extractAllNodesThatMatch(new NodeFilter() {
31. //实现该方法,用以过滤标签
32. public boolean accept(Node node) {
33. if (node instanceof LinkTag)//<A>标记
34. return true;
35. return false;
36. }
37. });
38. // 打印
39. for (int i = 0; i < nodeList.size(); i++) {
40. LinkTag n = (LinkTag) nodeList.elementAt(i);
41. System.out.print(n.getStringText() + " ==>> ");
42. System.out.println(n.extractLink());
43. }
44. } catch (Exception e) {
45. e.printStackTrace();
46. }
47.
48. } catch (Exception e) {
49. e.printStackTrace();
50. }
51. }
52. }
------解决方案--------------------
学习了