Python爬虫实战项目:从零开发一个新闻资讯聚合采集器
从零构建一个多源新闻资讯聚合采集器,系统讲解网络请求调度、正文结构化解析、URL与内容指纹去重以及SQLite持久化存储的完整实现方案。
开发新闻资讯聚合采集器的核心任务,是解决多站点网络请求的稳定性、正文与元数据的结构化提取、多源重复资讯的指纹判重,以及标准化入库持久化。本文将通过模块化设计,一步步实现一个轻量可扩展的 Python 新闻采集系统,覆盖从源站配置、HTTP调度抓取、DOM清洗解析到 SQLite 幂等存储的完整落地流程。
一、系统架构设计与技术选型权衡
新闻资讯聚合采集器与普通单页面抓取脚本不同,它需要周期性对多个目标源进行扫描,统一清洗异构站点的 HTML 结构,并保证相同内容不会被反复插入数据库。因此,项目整体划分为四层:配置管理层、请求获取层、解析清洗层和持久化存储层。
同步请求与异步请求的选型差异
在设计资讯采集器时,网络请求模型通常有两种主流做法:一种是基于 requests 的同步多线程模型;另一种是基于 aiohttp 或 httpx 的异步协程模型。在同样采集 10 个常见新闻源、每个源抓取 20 条资讯的相同工作条件下,两者在开发复杂度、系统控制粒度及资源开销上有本质差异:
| 对比维度 | 同步模型(requests + 线程池) | 异步协程模型(aiohttp / httpx) |
|---|---|---|
| 并发机制 | 依靠操作系统线程调度,每个线程独立持有阻塞式 I/O 连接。 | 基于单个事件循环(Event Loop)与非阻塞套接字,轻量级并发。 |
| 开发与调试难度 | 极低。代码线性执行,异常堆栈直接对应发生位置,排查网络和解析 bug 直观。 | 中等偏高。需要管理 async/await 上下文,处理复杂的任务取消与事件循环生命周期。 |
| 频率限制与防封控 | 容易在单个源的任务中插入精确的 time.sleep(),不同站点的抓取节律易隔离。 |
需要配合信号量(Semaphore)和令牌桶限流,稍有不慎容易瞬时迸发过量请求导致封禁。 |
| 资源开销与适用场景 | 适合站点数量中等(几十个以内)、单次采集耗时要求在分钟级别的新闻聚合器。 | 适合监控数百个站点、毫秒级响应的大规模全网爬虫系统。 |
对于新闻资讯聚合任务,站点往往对高频访问有敏感的限流保护,毫秒级的高并发拉取容易触发目标站的反爬虫封锁。因此,本项目选用结构清晰、调试直观且更易加入站点间隔控制的 requests.Session 方案,将工程重心放在数据清洗的鲁棒性与去重存储上。
二、工程搭建与环境准备
本项目仅依赖三个核心三方库:处理 HTTP 请求的 requests、处理 HTML 树状解析的 beautifulsoup4 以及底层加速解析器 lxml。数据库直接选用 Python 内置的 sqlite3 模块,避免部署外部数据库的运维成本。
在终端中执行以下命令安装依赖:
pip install requests beautifulsoup4 lxml
为了保证模块职责边界清晰,我们将工程组织为以下目录结构:
news_spider/
├── config.py # 新闻源规则定义与公共参数
├── fetcher.py # HTTP网络请求与重试处理
├── parser.py # HTML正文解析与指纹计算
├── storage.py # SQLite数据库持久化操作
└── main.py # 聚合调度器与主程序入口
三、核心模块的具体代码实现
1. 规则与常量配置(config.py)
新闻源通常具有不同的 DOM 标签和路径规则。我们将目标站点的列表页地址、条目选择器、标题选择器和正文选择器配置化,后续增加新站点时无需修改核心业务代码。
# config.py
# 目标新闻源规则配置与全局参数
DEFAULT_HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}
# 数据库存储文件路径
DB_PATH = "news_aggregation.db"
# 新闻源抓取规则定义
NEWS_SOURCES = [
{
"source_name": "开源资讯汇",
"base_url": "https://example.com/opensource",
"entry_url": "https://example.com/opensource/news",
"list_selector": "article.news-item",
"title_selector": "h2.news-title a",
"url_attr": "href",
"date_selector": ".publish-time",
"content_selector": ".news-summary"
},
{
"source_name": "科技观察报",
"base_url": "https://example.org/tech",
"entry_url": "https://example.org/tech/feed",
"list_selector": "div.post-card",
"title_selector": "h3.entry-title a",
"url_attr": "href",
"date_selector": "span.meta-date",
"content_selector": "div.entry-excerpt"
}
]
2. 稳健的网络请求层(fetcher.py)
网络请求的核心是处理超时、网络波动和编码错误。fetcher.py 维护一个 requests.Session 实例,通过连接池复用 TCP 握手,同时支持遇到 5xx 错误或连接超时时的自动退避重试。
# fetcher.py
import time
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from config import DEFAULT_HEADERS
class NewsFetcher:
def __init__(self, timeout=10, max_retries=3):
self.timeout = timeout
self.session = requests.Session()
self.session.headers.update(DEFAULT_HEADERS)
# 配置底层传输适配器的重试策略
retry_strategy = Retry(
total=max_retries,
backoff_factor=1, # 重试间隔依次为 1s, 2s, 4s
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
self.session.mount("http://", adapter)
self.session.mount("https://", adapter)
def fetch_html(self, url):
"""请求指定URL并返回合法的HTML文本"""
try:
response = self.session.get(url, timeout=self.timeout)
response.raise_for_status()
# 解决中文页面常见的 ISO-8859-1 或 GBK 乱码问题
if response.encoding == "ISO-8859-1":
response.encoding = response.apparent_encoding or "utf-8"
return response.text
except requests.exceptions.RequestException as e:
print(f"[请求异常] 获取页面失败 {url},原因: {e}")
return None
def close(self):
self.session.close()
3. 正文清洗与去重指纹计算(parser.py)
从 HTML 中提取新闻数据时,主要面临三个问题:相对 URL 路径转换、正文中多余换行与空格清理,以及跨站点重复资讯的指纹提取。
# parser.py
import re
import hashlib
from urllib.parse import urljoin
from bs4 import BeautifulSoup
class NewsParser:
@staticmethod
def clean_text(text):
"""清洗文本中的冗余换行、制表符及连续多余空格"""
if not text:
return ""
# 替换多种连续空白为单个空格,剔除首尾留白
cleaned = re.sub(r"\s+", " ", text)
return cleaned.strip()
@staticmethod
def generate_fingerprint(url, title):
"""基于标准化 URL 和标题计算 SHA-256 唯一指纹"""
normalized_str = f"{url.strip().lower()}|{title.strip()}"
return hashlib.sha256(normalized_str.encode("utf-8")).hexdigest()
def parse_list(self, html, rule):
"""根据配置规则从列表页提取新闻项列表"""
if not html:
return []
soup = BeautifulSoup(html, "lxml")
items = soup.select(rule["list_selector"])
results = []
for item in items:
title_node = item.select_one(rule["title_selector"])
if not title_node:
continue
title = self.clean_text(title_node.get_text())
raw_url = title_node.get(rule["url_attr"], "").strip()
if not title or not raw_url:
continue
# 转换为绝对路径
full_url = urljoin(rule["base_url"], raw_url)
# 提取时间
date_node = item.select_one(rule.get("date_selector", ""))
pub_date = self.clean_text(date_node.get_text()) if date_node else "未知"
# 提取简短正文或摘要
content_node = item.select_one(rule.get("content_selector", ""))
content = self.clean_text(content_node.get_text()) if content_node else ""
# 生成判重哈希
hash_id = self.generate_fingerprint(full_url, title)
results.append({
"hash_id": hash_id,
"source": rule["source_name"],
"title": title,
"url": full_url,
"publish_time": pub_date,
"content": content
})
return results
4. 数据去重与 SQLite 持久化(storage.py)
在数据库层面,利用 hash_id 的 UNIQUE 约束,并搭配 INSERT OR IGNORE 语法,能够以极低的代码量实现可靠的数据幂等写入。即使多次运行采集器,已存在的资讯条目也不会产生冲突或导致程序崩溃。
# storage.py
import sqlite3
from datetime import datetime
class NewsStorage:
def __init__(self, db_path):
self.db_path = db_path
self._init_table()
def _get_connection(self):
return sqlite3.connect(self.db_path)
def _init_table(self):
"""创建新闻存储表及唯一索引"""
create_sql = """
CREATE TABLE IF NOT EXISTS news_articles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
hash_id TEXT UNIQUE NOT NULL,
source TEXT NOT NULL,
title TEXT NOT NULL,
url TEXT NOT NULL,
publish_time TEXT,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
create_index_sql = """
CREATE INDEX IF NOT EXISTS idx_news_source ON news_articles(source);
"""
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(create_sql)
cursor.execute(create_index_sql)
conn.commit()
def save_articles(self, articles):
"""
批量持久化新闻记录
返回值: (新增条数, 忽略条数)
"""
if not articles:
return 0, 0
insert_sql = """
INSERT OR IGNORE INTO news_articles
(hash_id, source, title, url, publish_time, content)
VALUES (?, ?, ?, ?, ?, ?);
"""
data = [
(
a["hash_id"],
a["source"],
a["title"],
a["url"],
a["publish_time"],
a["content"]
)
for a in articles
]
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.executemany(insert_sql, data)
inserted_count = cursor.rowcount
conn.commit()
ignored_count = len(articles) - inserted_count
return inserted_count, ignored_count
def get_latest_news(self, limit=10):
"""查询最新收录的新闻记录"""
query_sql = """
SELECT source, title, publish_time, url, created_at
FROM news_articles
ORDER BY id DESC LIMIT ?;
"""
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(query_sql, (limit,))
return cursor.fetchall()
5. 多源聚合调度与主程序运行(main.py)
调度器 main.py 串联采集、解析、存储各个环节,并在每次请求之间加入轻微休眠,兼顾抓取效率与对目标站点的友好性。
# main.py
import time
from config import NEWS_SOURCES, DB_PATH
from fetcher import NewsFetcher
from parser import NewsParser
from storage import NewsStorage
def run_collector():
print("=" * 60)
print("新闻资讯聚合采集器启动运行...")
print("=" * 60)
fetcher = NewsFetcher(timeout=10, max_retries=3)
parser = NewsParser()
storage = NewsStorage(db_path=DB_PATH)
total_fetched = 0
total_saved = 0
total_skipped = 0
try:
for rule in NEWS_SOURCES:
source_name = rule["source_name"]
entry_url = rule["entry_url"]
print(f"\n[正在采集] 目标站点: {source_name} -> {entry_url}")
# 1. 发起网络请求获取 HTML
html = fetcher.fetch_html(entry_url)
if not html:
print(f"[跳过] 无法获取 {source_name} 页面内容")
continue
# 2. 结构化解析
articles = parser.parse_list(html, rule)
print(f"[解析完成] 匹配到 {len(articles)} 条资讯数据")
# 3. 存储与判重
inserted, ignored = storage.save_articles(articles)
print(f"[入库结果] 新增入库: {inserted} 条,跳过重复: {ignored} 条")
total_fetched += len(articles)
total_saved += inserted
total_skipped += ignored
# 站点间隔友好休眠 (1.5秒)
time.sleep(1.5)
finally:
fetcher.close()
print("\n" + "=" * 60)
print("采集任务执行完毕汇总:")
print(f"总发现条目: {total_fetched} | 新增收录: {total_saved} | 判定重复: {total_skipped}")
print("=" * 60)
# 打印数据库最近 5 条记录进行抽样验证
print("\n[数据库最新收录抽样验证]:")
records = storage.get_latest_news(limit=5)
for idx, (src, title, pub_date, url, created) in enumerate(records, 1):
print(f"{idx}. [{src}] {title}")
print(f" 发布时间: {pub_date} | 抓取时间: {created}")
print(f" 链接: {url}\n")
if __name__ == "__main__":
run_collector()
四、运行验证与结果检查
在工程根目录下执行主程序启动采集器:
python main.py
程序正常运行时的控制台终端输出示例如下:
============================================================
新闻资讯聚合采集器启动运行...
============================================================
[正在采集] 目标站点: 开源资讯汇 -> https://example.com/opensource/news
[解析完成] 匹配到 15 条资讯数据
[入库结果] 新增入库: 15 条,跳过重复: 0 条
[正在采集] 目标站点: 科技观察报 -> https://example.org/tech/feed
[解析完成] 匹配到 12 条资讯数据
[入库结果] 新增入库: 12 条,跳过重复: 0 条
============================================================
采集任务执行完毕汇总:
总发现条目: 27 | 新增收录: 27 | 判定重复: 0
============================================================
[数据库最新收录抽样验证]:
1. [科技观察报] 新型轻量级推理模型正式开源发布
发布时间: 2026-10-15 | 抓取时间: 2026-10-17 21:30:05
链接: https://example.org/tech/feed/post-1092
2. [开源资讯汇] Python 高并发架构在物联网数据清洗中的应用实践
发布时间: 2026-10-14 | 抓取时间: 2026-10-17 21:30:03
链接: https://example.com/opensource/news/art-8821
如果紧接着再次执行一次 python main.py,因为所有资讯的 hash_id 均已存在于 SQLite 中,入库结果会显示为新增 0 条,跳过 27 条,证实幂等去重逻辑正常生效。
sqlite3 客户端直接查验数据库内容:
sqlite3 news_aggregation.db "SELECT source, count(*) FROM news_articles GROUP BY source;"
五、总结与演进方向
开发一个可靠的新闻聚合采集器,最关键的不是复杂的爬虫框架,而是保持“请求-解析-清洗-判重-入库”整个链路的稳定与解耦。针对后续业务规模的增长,可以在现有代码的基础上从以下三个方向进行渐进式演进:
通过本文完成的 NewsAggregator 框架,你已经掌握了一个可用、稳健的新闻聚合系统的基础骨架。将其部署在服务器并配置 Linux Crontab 定时调度后,即可持续自动化沉淀各大资讯源的结构化数据。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













