随笔 - 434,  文章 - 0,  评论 - 463,  阅读 - 46万

本项目中需要用到两个第三方jar包,分别为 jsoup 和 commons-io。

jsoup的作用是为了解析网页, commons-io 是为了把数据保存到本地。

1.爬取贴吧

第一步,打开eclipse,新建一个java项目,名字就叫做 pachong:

然后,新建一个类,作为我们程序的入口。

这个作为入口类,里面就写一个main方法即可。

public class StartUp {

	public static void main(String[] args) {
		
	}
}

第二步,导入我们的依赖,两个jar包:

右键jar包,Build path , add to Build path

接着,我们试着搜索一下动漫吧的数据:

https://tieba.baidu.com/f?kw=%B6%AF%C2%FE&tpl=5

public class StartUp {

	public static void main(String[] args) {
		String url = "https://tieba.baidu.com/f?kw=%B6%AF%C2%FE&tpl=5";
		Connection connect = Jsoup.connect(url);
		System.out.println(connect);
	}
}

如果能够成功打印出来链接,说明我们的连接测试是成功的!

然后,我们调用connect的get方法,获取链接到的数据:

Document document = connect.get(); 

这边需要抛出一个异常,而且是强制性的,因为有可能会获取失败。这边我们直接抛出去,不去捕获。

public class StartUp {

	public static void main(String[] args) throws IOException {
		String url = "https://tieba.baidu.com/f?kw=%B6%AF%C2%FE&tpl=5";
		Connection connect = Jsoup.connect(url);
		System.out.println(connect);
		
		Document document = connect.get(); 
		System.out.println(document);
	}
}

打印出来的结果:

可见,document对象装的就是一个完整HTML页面。

在这里,我们想要拿到的第一个数据,就是所有帖子的标题:

我们发现,每一个标题都是一个a连接,class为j_th_tit 。

下一步我们就考虑获取所有class为 j_th_tit 的元素。

我们发现,document对象给我们提供了 getElementsByClass 的方法,顾名思义,就是获取class为 XXX 的元素。

Elements titles = document.getElementsByClass("j_th_tit");

接着,遍历titles,打印出每一个标题的名称:

for (int i = 0; i < titles.size(); i++) {
	System.out.println(titles.get(i).attr("title"));
}

当前代码:

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;


public class StartUp {

	public static void main(String[] args) throws IOException {
		String url = "https://tieba.baidu.com/f?kw=%B6%AF%C2%FE&tpl=5";
		Connection connect = Jsoup.connect(url);
		
		Document document = connect.get(); 
		
		Elements titles = document.getElementsByClass("j_th_tit");
		
		for (int i = 0; i < titles.size(); i++) {
			System.out.println(titles.get(i).attr("title"));
		}
		
	}
}
posted on   剽悍一小兔  阅读(42)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示