今天重新搜索了一下,发现jsoup很容易上手~选择器很好很强大。
支持DOM和选择器两种模式
1、下载
jsoup的网站很简洁: http://jsoup.org/
入门做的很不错: http://jsoup.org/cookbook/
2、简单的例子
以下示例用于抓取iteye首页的新闻及连接,共使用了3种方式获取元素:
选择器 |
用组件的Id |
用组件的class |
package tests; import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class EgParseItEyeNews { public static void main(String[] args) throws IOException { String url = "http://www.iteye.com/"; // 不加userAgent会被视为爬虫。。。。。 Document doc = Jsoup.connect(url) .userAgent("Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1 ") .get(); // Element news = doc.getElementById("news"); //1、通过ID Elements newsConents=doc.getElementsByClass("news_content");//2、通过class Element news=newsConents.first(); if (news == null) System.out.println(doc); else { // System.out.println(news); // System.out.println("end of news****************\n"); Elements elems = news.select("a"); // 3、通过选择器 , 把链接都提取出来 for (Element element : elems) { System.out.println(element.text() + " \t链接为:" + element.attr("href")); } } } }
输出如下:
- 轻量级JavaWeb开发框架EWeb4J作者赖伟威专访 链接为:http://www.iteye.com/magazines/105
- [详情] 链接为:http://www.iteye.com/magazines/105
- 12月TIOBE编程语言排行榜:年度语言非ObjC莫属 链接为:http://www.iteye.com/news/26673
- [详情] 链接为:http://www.iteye.com/news/26673
- JDK6明年2月停止更新,甲骨文呼吁尽快升级至7 链接为:http://www.iteye.com/news/26683
- [详情] 链接为:http://www.iteye.com/news/26683
。。。好多重复的链接啊!!!将选择器重的代码改为:
Elements elems = news.select("dt>a"); // 3、通过选择器 , 把链接都提取出来
使得只选择的链接为dt标签的直接子类即可去掉[详情]项,更多选项如后文所示。
3、选择器字符串的语法
这里有实例介绍: http://jsoup.org/cookbook/extracting-data/selector-syntax
用法详解: http://jsoup.org/apidocs/org/jsoup/select/Selector.html
下图是从上面的网址抠出来的:
4、在线文档
http://jsoup.org/apidocs/