Jsoup网页抓取工具demo

本文介绍了一个使用Java和Jsoup实现的网页抓取工具demo,该工具通过模拟浏览器访问方式,成功抓取了开源中国网站上的项目信息,并展示了如何解析和提取网页中的指定元素。

Jsoup网页抓取工具demo

1.项目是maven项目

2.测试的主函数代码如下:

package www.tydic.com.test;

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 Test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		final String url = "https://www.oschina.net/project/lang/19/java";
		try {
			/**
			 * 使用浏览器模式访问网址,避免403错误
			 */
			Document doc = Jsoup.connect(url)
					.userAgent(
							"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31")
					.get();
			Elements container = doc.getElementsByClass("ProjectList");
			Document containerDoc = Jsoup.parse(container.toString());
			Elements module = containerDoc.getElementsByClass("List");
			Document moduledoc = Jsoup.parse(module.toString());
			/**
			 * 获取class为List的ul中的列表,然后进行遍历
			 */
			Elements recommElement = moduledoc.select(".recomm");
			for (Element elem : recommElement) {
				 Document clearfixliDoc = Jsoup.parse(elem.toString());
				 //获取标题
				 Elements h3_text = clearfixliDoc.select("h3");
				 //获取简介
				 Elements detail_text = clearfixliDoc.select(".detail");
				 Document hrefDoc = Jsoup.parse(detail_text.toString());
				 //获取更多信息的连接
				 Element moreEle = hrefDoc.select("a").first();
				 String absHref = moreEle.attr("href");
				 System.out.println("获取相应的标题:"+h3_text.text());
				 System.out.println("获取详情简介:"+detail_text.text());
				 System.out.println("获取更多:"+moreEle.text());
				 System.out.println("获取更多信息的连接:"+"https://www.oschina.net"+absHref);
				 System.out.println("=================================");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

主要是获取开源中国的一些相关信息。

对于分页内容暂时还没思路,这个只是一个简单demo

转载于:https://my.oschina.net/u/1399599/blog/809779

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值