之前用过HTMLParser,许久不更新的东西了,印象中也没那么好用。
今天重新搜索了一下,发现jsoup很容易上手~选择器很好很强大。
支持DOM和选择器两种模式
1、下载
jsoup的网站很简洁: http://jsoup.org/
入门做的很不错: http://jsoup.org/cookbook/
2、简单的例子
以下示例用于抓取iteye首页的新闻及连接,共使用了3种方式获取元素:
今天重新搜索了一下,发现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"));
- }
- }
- }
- }
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"));
}
}
}
}