使用jsoup分析网页

之前用过HTMLParser,许久不更新的东西了,印象中也没那么好用。
今天重新搜索了一下,发现jsoup很容易上手~选择器很好很强大。
支持DOM和选择器两种模式


1、下载
jsoup的网站很简洁: http://jsoup.org/
入门做的很不错: http://jsoup.org/cookbook/

2、简单的例子
以下示例用于抓取iteye首页的新闻及连接,共使用了3种方式获取元素:
选择器
用组件的Id
用组件的class

Java代码 复制代码 收藏代码
  1. package tests;
  2. import java.io.IOException;
  3. import org.jsoup.Jsoup;
  4. import org.jsoup.nodes.Document;
  5. import org.jsoup.nodes.Element;
  6. import org.jsoup.select.Elements;
  7. public class EgParseItEyeNews {
  8. public static void main(String[] args) throws IOException {
  9. String url = "http://www.iteye.com/";
  10. // 不加userAgent会被视为爬虫。。。。。
  11. Document doc = Jsoup.connect(url)
  12. .userAgent("Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1 ")
  13. .get();
  14. // Element news = doc.getElementById("news"); //1、通过ID
  15. Elements newsConents=doc.getElementsByClass("news_content");//2、通过class
  16. Element news=newsConents.first();
  17. if (news == null)
  18. System.out.println(doc);
  19. else {
  20. // System.out.println(news);
  21. // System.out.println("end of news****************\n");
  22. Elements elems = news.select("a"); // 3、通过选择器 , 把链接都提取出来
  23. for (Element element : elems) {
  24. System.out.println(element.text() + " \t链接为:" + element.attr("href"));
  25. }
  26. }
  27. }
  28. }
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"));
			}
		}

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值