ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

Java Spring Boot 爬虫技术全面介绍

Java Spring Boot 爬虫技术全面介绍 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 HttpClientPageProcessor解析页面内容提取数据和新的链接Scheduler管理待抓取的 URL去重和调度Pipeline处理爬取结果存储到文件/数据库/Redis 等Maven 依赖dependencygroupIdus.codecraft/groupIdartifactIdwebmagic-core/artifactIdversion0.10.0/version/dependencydependencygroupIdus.codecraft/groupIdartifactIdwebmagic-extension/artifactIdversion0.10.0/version/dependencyJsoup — 轻量级 HTML 解析利器Jsoup 是 Java 世界最常用的 HTML 解析库零依赖仅 280KB支持 CSS 选择器语法类似 jQuery可直接从 URL、文件或字符串加载 HTML。dependencygroupIdorg.jsoup/groupIdartifactIdjsoup/artifactIdversion1.17.2/version/dependencySelenium / Playwright — 动态页面渲染对于 JavaScript 动态渲染的页面需要借助浏览器自动化工具Selenium社区成熟支持多语言多浏览器Java 中通过WebDriver驱动 Chrome/FirefoxPlaywright微软出品支持 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. 页面处理器PageProcessorComponentpublicclassArticlePageProcessorimplementsPageProcessor{privateSitesiteSite.me().setRetryTimes(3).setSleepTime(1000).setUserAgent(Mozilla/5.0 (Windows NT 10.0; Win64; x64));Overridepublicvoidprocess(Pagepage){// 提取详情页链接加入爬取队列page.addTargetRequests(page.getHtml().links().regex(https://www\\.example\\.com/article/\\d).all());// 提取页面数据page.putField(title,page.getHtml().xpath(//h1[classtitle]/text()).toString());page.putField(content,page.getHtml().xpath(//div[classcontent]/tidyText()).toString());if(page.getResultItems().get(title)null){page.setSkip(true);// 跳过无效页面}}OverridepublicSitegetSite(){returnsite;}}2. 数据管道PipelineComponentpublicclassArticlePipelineimplementsPipeline{AutowiredprivateArticleMapperarticleMapper;Overridepublicvoidprocess(ResultItemsresultItems,Tasktask){ArticlearticlenewArticle();article.setTitle(resultItems.get(title));article.setContent(resultItems.get(content));article.setCreateTime(newDate());articleMapper.insert(article);}}3. 定时任务调度ComponentpublicclassCrawlerTask{AutowiredprivateArticlePageProcessorprocessor;AutowiredprivateArticlePipelinepipeline;Scheduled(fixedDelay600000)// 每10分钟执行一次publicvoidcrawl(){Spider.create(processor).addUrl(https://www.example.com).addPipeline(pipeline).thread(5).run();}}4. 启动类SpringBootApplicationMapperScan(com.example.crawler.dao)EnableSchedulingpublicclassCrawlerApplication{publicstaticvoidmain(String[]args){SpringApplication.run(CrawlerApplication.class,args);}}使用 Jsoup 的轻量级方案如果不需要 WebMagic 这样的完整框架也可以直接用 Spring Boot Jsoup HttpClient 实现简单爬虫ServicepublicclassSimpleCrawlerService{AutowiredprivateCloseableHttpClienthttpClient;publicvoidcrawl(Stringurl)throwsIOException{HttpGetrequestnewHttpGet(url);request.setHeader(User-Agent,Mozilla/5.0 ...);HttpResponseresponsehttpClient.execute(request);StringhtmlEntityUtils.toString(response.getEntity(),UTF-8);DocumentdocJsoup.parse(html);Stringtitledoc.title();Elementsarticlesdoc.select(div.article-item);for(Elementitem:articles){Stringheadingitem.select(h2).text();Stringlinkitem.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.ymlcrawler:user-agent-list:-Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...-Mozilla/5.0 (Macintosh; Intel Mac OS X ...) ...request-delay:1000timeout:5000新兴框架GreenFingerGreenFinger 是 2026 年出现的高性能分布式爬虫框架原生集成 Spring Boot提供 Angular 可视化 Web UI支持 Playwright/Selenium/HtmlUnit 三种渲染引擎内置 Bloom Filter RocksDB 实现十亿级 URL 去重适合企业级大规模爬取场景。dependencygroupIdcom.github.paganini2008/groupIdartifactIdgreenfinger-spring-boot-starter/artifactIdversion1.0.0-SNAPSHOT/version/dependency⚠️ 合规红线无论使用哪种技术方案爬虫开发必须遵守法律法规遵守目标网站的robots.txt协议控制爬取频率避免对目标服务器造成过大压力禁止爬取个人隐私数据、涉密信息、付费加密内容爬取数据不得用于侵权、违法盈利等用途选型建议总结场景推荐方案静态页面、快速开发Spring Boot Jsoup HttpClient中大规模、结构化爬取Spring Boot WebMagic MyBatis动态 JS 渲染页面WebMagic Selenium 或 Playwright企业级分布式爬取GreenFinger 或 Apache Nutch轻量脚本、一次性任务Jsoup 单独使用
返回列表