- 网络数据采集技术:Java网络爬虫实战
- 钱洋等
- 603字
- 2025-02-17 21:43:45
2.5 集合
网络爬虫离不开对集合的操作,具体涉及List、Set、Queue和Map等集合,这些集合都位于java.util包。
2.5.1 List和Set集合
List集合的特征是其元素以线性方式存储,集合中可以存放重复对象。相比而言,Set集合中的元素不按特定的方式排序,并且没有重复对象。在网络爬虫中,可以使用List<String>存储待采集的URL列表,如程序2-6所示。
程序2-6

Set集合存储不重复的URL,如程序2-7所示。
程序2-7

图2.9所示为程序2-7的执行结果,可以看出Set集合自动过滤了重复的元素。

图2.9 Set集合案例
2.5.2 Map集合
Map集合是一种把键对象和值对象进行映射的集合,它的每个元素都包含一个键对象key和值对象value。其中,键对象不可以重复。Map集合不仅在网络爬虫中常用,也常在文本挖掘算法编写中使用(如TF-IDF)。在网络爬虫中,可以使用Map集合过滤一些重复数据,但并不建议使用Map集合对大规模数据去重过滤,原因是Map集合有空间大小的限制。例如,使用网络爬虫采集帖子时,可能遇到置顶帖,而置顶帖在其他页面中也会出现,使用Map集合可以过滤已采集的置顶帖。程序2-8为Map集合使用的方式。
程序2-8


2.5.3 Queue集合
Queue(队列)集合使用链表结构存储数据,它只允许在表的前端进行删除操作,而在表的后端进行插入操作,即表的两端操作。Queue集合常见的操作方法包括添加元素、移除队头元素和判断队列是否为空等,具体使用方法如表2.1所示。
表2.1 Queue集合常用操作方法

在网络爬虫中,Queue集合常用来存放待采集的URL,如程序2-9所示。
程序2-9


执行程序2-9,会在控制台得到如图2.10所示的结果。

图2.10 Queue集合案例运行结果