Java Spring Boot 爬虫技术全面介绍
在 Java 生态中,Spring Boot 凭借其自动配置、依赖注入、定时任务等开箱即用的能力,成为构建企业级爬虫系统的理想框架。下面从工具选型、架构设计、代码实现到反爬策略,系统梳理 Spring Boot 爬虫开发的核心知识。
为什么用 Spring Boot 做爬虫
Spring Boot 为爬虫开发提供了天然的基础设施优势:
- 依赖注入(DI) :通过
@Autowired管理 HttpClient、解析器、数据库连接等组件,解耦清晰 - 定时任务 :
@Scheduled或ScheduledExecutorService可轻松实现周期性爬取 - 配置外部化 :
application.yml统一管理爬取频率、超时时间、代理等参数,支持多环境切换 - 监控运维 :集成
spring-boot-starter-actuator,通过/actuator/metrics、/actuator/health实时监控爬虫状态 - 数据持久化:无缝集成 MyBatis、JPA、Redis、MongoDB 等,爬取数据直接入库
核心工具与框架
WebMagic --- Java 爬虫首选框架
WebMagic 是 Java 生态中最成熟的开源爬虫框架,架构参照 Python 的 Scrapy,由核心模块和扩展模块组成。
四大核心组件:
| 组件 | 职责 |
|---|---|
| Downloader | 从互联网下载页面,默认使用 Apache HttpClient |
| PageProcessor | 解析页面内容,提取数据和新的链接 |
| Scheduler | 管理待抓取的 URL,去重和调度 |
| Pipeline | 处理爬取结果,存储到文件/数据库/Redis 等 |
Maven 依赖:
xml
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-core</artifactId>
<version>0.10.0</version>
</dependency>
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-extension</artifactId>
<version>0.10.0</version>
</dependency>
Jsoup --- 轻量级 HTML 解析利器
Jsoup 是 Java 世界最常用的 HTML 解析库,零依赖,仅 280KB,支持 CSS 选择器语法(类似 jQuery),可直接从 URL、文件或字符串加载 HTML。
xml
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.17.2</version>
</dependency>
Selenium / Playwright --- 动态页面渲染
对于 JavaScript 动态渲染的页面,需要借助浏览器自动化工具:
- Selenium :社区成熟,支持多语言多浏览器,Java 中通过
WebDriver驱动 Chrome/Firefox - Playwright:微软出品,支持 Chromium/Firefox/WebKit 三大内核,自动等待元素加载,性能优于 Selenium,是处理动态页面的现代化首选
Apache HttpClient --- 底层 HTTP 通信
Java 原生 HttpURLConnection 功能有限,实际项目中通常使用 Apache HttpClient 或 OkHttp,支持连接池、Cookie 管理、代理、超时控制等高级特性。
Spring Boot 集成爬虫的架构设计
一个规范的 Spring Boot 爬虫项目通常采用以下分层结构:
com.example.crawler
├── config/ # 配置类(HttpClient、线程池、代理等)
├── controller/ # REST 接口(启动/停止/查询爬虫任务)
├── service/ # 业务逻辑(爬虫调度、数据清洗)
├── processor/ # 页面处理器(PageProcessor 实现)
├── pipeline/ # 数据管道(存储到 MySQL/Redis/ES)
├── model/ # 实体类
├── dao/ # 数据访问层(MyBatis Mapper)
└── task/ # 定时任务(@Scheduled 触发爬取)
实战代码示例:Spring Boot + WebMagic + MyBatis
以下演示一个完整的集成方案,爬取网页内容并持久化到 MySQL。
1. 页面处理器(PageProcessor)
java
@Component
public class ArticlePageProcessor implements PageProcessor {
private Site site = Site.me()
.setRetryTimes(3)
.setSleepTime(1000)
.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
@Override
public void process(Page page) {
// 提取详情页链接,加入爬取队列
page.addTargetRequests(
page.getHtml().links().regex("https://www\\.example\\.com/article/\\d+").all()
);
// 提取页面数据
page.putField("title", page.getHtml().xpath("//h1[@class='title']/text()").toString());
page.putField("content", page.getHtml().xpath("//div[@class='content']/tidyText()").toString());
if (page.getResultItems().get("title") == null) {
page.setSkip(true); // 跳过无效页面
}
}
@Override
public Site getSite() {
return site;
}
}
2. 数据管道(Pipeline)
java
@Component
public class ArticlePipeline implements Pipeline {
@Autowired
private ArticleMapper articleMapper;
@Override
public void process(ResultItems resultItems, Task task) {
Article article = new Article();
article.setTitle(resultItems.get("title"));
article.setContent(resultItems.get("content"));
article.setCreateTime(new Date());
articleMapper.insert(article);
}
}
3. 定时任务调度
java
@Component
public class CrawlerTask {
@Autowired
private ArticlePageProcessor processor;
@Autowired
private ArticlePipeline pipeline;
@Scheduled(fixedDelay = 600000) // 每10分钟执行一次
public void crawl() {
Spider.create(processor)
.addUrl("https://www.example.com")
.addPipeline(pipeline)
.thread(5)
.run();
}
}
4. 启动类
java
@SpringBootApplication
@MapperScan("com.example.crawler.dao")
@EnableScheduling
public class CrawlerApplication {
public static void main(String[] args) {
SpringApplication.run(CrawlerApplication.class, args);
}
}
使用 Jsoup 的轻量级方案
如果不需要 WebMagic 这样的完整框架,也可以直接用 Spring Boot + Jsoup + HttpClient 实现简单爬虫:
java
@Service
public class SimpleCrawlerService {
@Autowired
private CloseableHttpClient httpClient;
public void crawl(String url) throws IOException {
HttpGet request = new HttpGet(url);
request.setHeader("User-Agent", "Mozilla/5.0 ...");
HttpResponse response = httpClient.execute(request);
String html = EntityUtils.toString(response.getEntity(), "UTF-8");
Document doc = Jsoup.parse(html);
String title = doc.title();
Elements articles = doc.select("div.article-item");
for (Element item : articles) {
String heading = item.select("h2").text();
String link = item.select("a").attr("abs:href");
// 存储数据...
}
}
}
动态页面处理
对于 React/Vue 等前端框架渲染的动态页面,HTTP 请求只能获取空壳 HTML,需要浏览器渲染引擎:
- 抓包分析 API:优先通过 F12 开发者工具找到数据接口,直接用 HttpClient 请求 JSON,效率最高
- Selenium 方案 :通过
WebDriver获取渲染后的pageSource,再用 Jsoup 解析 - WebMagic + Selenium 扩展 :引入
webmagic-selenium模块,自定义 Downloader 使用RemoteWebDriver下载页面
反爬策略与应对
网站常见的反爬手段及 Java 中的应对方案:
| 反爬手段 | 应对策略 |
|---|---|
| User-Agent 检测 | 在 Site 或请求头中伪装浏览器标识 |
| IP 频率限制 | 使用代理 IP 池轮换,设置 setSleepTime() 控制请求间隔 |
| Cookie/登录验证 | 通过 Site.setCookie() 或 Jsoup 的 .cookies() 维持会话 |
| 验证码 | 接入第三方打码平台或 OCR 识别 |
| JS 加密参数 | 逆向分析 JS 逻辑,用 Java 复现加密过程 |
配置示例(application.yml):
yaml
crawler:
user-agent-list:
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ..."
- "Mozilla/5.0 (Macintosh; Intel Mac OS X ...) ..."
request-delay: 1000
timeout: 5000
新兴框架:GreenFinger
GreenFinger 是 2026 年出现的高性能分布式爬虫框架,原生集成 Spring Boot,提供 Angular 可视化 Web UI,支持 Playwright/Selenium/HtmlUnit 三种渲染引擎,内置 Bloom Filter + RocksDB 实现十亿级 URL 去重,适合企业级大规模爬取场景。
xml
<dependency>
<groupId>com.github.paganini2008</groupId>
<artifactId>greenfinger-spring-boot-starter</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
⚠️ 合规红线
无论使用哪种技术方案,爬虫开发必须遵守法律法规:
- 遵守目标网站的
robots.txt协议 - 控制爬取频率,避免对目标服务器造成过大压力
- 禁止爬取个人隐私数据、涉密信息、付费加密内容
- 爬取数据不得用于侵权、违法盈利等用途
选型建议总结
| 场景 | 推荐方案 |
|---|---|
| 静态页面、快速开发 | Spring Boot + Jsoup + HttpClient |
| 中大规模、结构化爬取 | Spring Boot + WebMagic + MyBatis |
| 动态 JS 渲染页面 | WebMagic + Selenium 或 Playwright |
| 企业级分布式爬取 | GreenFinger 或 Apache Nutch |
| 轻量脚本、一次性任务 | Jsoup 单独使用 |