java使用jsoup爬虫入门

本文介绍如何在Maven项目中使用Jsoup进行网页抓取,包括添加依赖、解析优快云首页的文章标题与链接,并将信息保存到本地文本文件,同时下载页面中的特定图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、maven项目里pom添加jsoup依赖

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.9.2</version>
</dependency>

二、以csdn网址为例,获取页面,使用dom获取内容,写入本地

public class JsoupDemo {
	private static OutputStream os;

	public static void main(String[] args) {
		try {
			Document doc = Jsoup.connect("https://www.youkuaiyun.com/").get();
//			System.out.println(doc.title()); //优快云-专业IT技术社区
			//把文章标题和连接写入txt文件
			Element feedlist_id = doc.getElementById("feedlist_id");
			Elements h2 = feedlist_id.select("h2.csdn-tracking-statistics");
			Elements a = h2.select("a");
			//指定文件名及路径
			File file = new File("E:\\jsoup\\word\\test.txt"); 
			if (!file.exists()) {
				file.createNewFile();
			}
			//写入本地
			PrintWriter pw = new PrintWriter("E:\\jsoup\\word\\test.txt","UTF-8"); 
			for (Element element : a) {
				pw.println(element.text());
				pw.println(element.attr("href")); 
				pw.println("------------------------------------------------------------------------------------------------------------------------------------");
			}
			pw.close(); //关闭输出流
			//获取页面上的图片保存到本地
			Elements imgs = doc.select("img[src$=.png]");
			for (Element element : imgs) {
				String img = element.attr("src");
				String url = "http:"+img;
				System.out.println(url);
				System.out.println(url.indexOf("csdn"));
				if (url.indexOf("csdn")==-1) {
					continue;
				}
				URL u = new URL(url);
				URLConnection uc=u.openConnection();
		        //获取数据流
		        InputStream is=uc.getInputStream();
		        //获取后缀名
		        String imageName = img.substring(img.lastIndexOf("/") + 1,img.length());
		        //写入本地
		        os = new FileOutputStream(new File("E:\\jsoup\\img", imageName));
		        byte[] b = new byte[1024];
		        int i=0;
		        while((i=is.read(b))!=-1){
		          os.write(b, 0, i);
		        }
		        is.close();
		        os.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

三、效果如下



jsoup爬虫demo: https://download.youkuaiyun.com/download/qq_15260315/10524321
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值