




源码:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from bs4 import BeautifulSoup
import pandas as pd
from urllib.parse import urlparse
class NewsCrawler:
"""新闻爬虫类:封装请求、解析与保存功能"""
def __init__(self, base_url: str, output_file: str = "result.csv"):
"""
初始化爬虫
:param base_url: 目标网址
:param output_file: 保存的文件名
"""
self.base_url = base_url
self.output_file = output_file
self.session = self._create_session()
self.news_data = []
def _create_session(self) -> requests.Session:
"""创建并配置带有重试机制的 Session"""
session = requests.Session()
session.headers.update({
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"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",
})
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET"],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def fetch_html(self) -> str | None:
"""请求网页并返回 HTML 文本"""
try:
response = self.session.get(self.base_url, timeout=10)
response.raise_for_status()
response.encoding = response.apparent_encoding
print(f"状态码: {response.status_code}")
return response.text
except requests.exceptions.Timeout:
print("请求超时(已重试 3 次)")
except requests.exceptions.ConnectionError:
print("连接错误(已重试 3 次)")
except requests.exceptions.HTTPError as e:
print(f"HTTP 错误: {e}")
except requests.exceptions.RequestException as e:
print(f"请求异常: {e}")
return None
def _sanitize_text(self, text: str) -> str:
"""安全过滤:防止 CSV 注入,去除前后空格"""
if not text:
return ""
text = text.strip()
# 防止 Excel 解析为公式 (CSV Injection)
if text.startswith(("=", "+", "-", "@")):
text = f"'{text}"
return text
def parse_html(self, html: str) -> None:
"""解析 HTML,提取数据并存入 self.news_data"""
if not html:
return
soup = BeautifulSoup(html, "html.parser")
items = soup.find_all("div", class_="news-item")
for item in items:
title_tag = item.find("h2", class_="title")
time_tag = item.find("span", class_="time")
author_tag = item.find("span", class_="author")
a_tag = item.find("a")
# 提取并清洗文本
title = self._sanitize_text(title_tag.get_text() if title_tag else "")
publish_time = self._sanitize_text(time_tag.get_text() if time_tag else "")
author = self._sanitize_text(author_tag.get_text() if author_tag else "")
# 提取链接(简单的合法性校验)
link = a_tag.get("href", "") if a_tag else ""
if link and not link.startswith(("http://", "https://", "/")):
link = "" # 拒绝 javascript: 等非法协议
self.news_data.append({
"标题": title,
"时间": publish_time,
"作者": author,
"链接": link
})
print(f"成功提取 {len(self.news_data)} 条新闻数据。")
def save_to_csv(self) -> None:
"""使用 pandas 将数据保存到 CSV 文件"""
if not self.news_data:
print("没有数据可保存。")
return
df = pd.DataFrame(self.news_data)
try:
# utf-8-sig 保证 Excel 打开不乱码
df.to_csv(self.output_file, index=False, encoding="utf-8-sig")
print(f"数据已成功保存至: {self.output_file}\n")
print("数据预览:")
print(df.head())
except Exception as e:
print(f"保存文件失败: {e}")
def run(self) -> None:
"""执行完整的爬取流程"""
html = self.fetch_html()
if html:
self.parse_html(html)
self.save_to_csv()
if __name__ == "__main__":
# 使用面向对象的方式调用
crawler = NewsCrawler(base_url="http://localhost:8000", output_file="result.csv")
crawler.run()
from http.server import BaseHTTPRequestHandler, HTTPServer
class FakeNewsServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html; charset=utf-8")
self.end_headers()
html = """
<html><body>
<div class="news-list">
<div class="news-item"><h2 class="title">Python Vibe Coding 席卷全球</h2><span class="time">2026-11-20</span><span class="author">张三</span><a href="/news/1">阅读全文</a></div>
<div class="news-item"><h2 class="title">AI Agent 开发实战指南</h2><span class="time">2026-11-19</span><span class="author">李四</span><a href="/news/2">阅读全文</a></div>
<div class="news-item"><h2 class="title">大模型微调技术与应用</h2><span class="time">2026-11-18</span><span class="author">王五</span><a href="/news/3">阅读全文</a></div>
</div>
</body></html>
结果:



转载自 CSDN-专业IT技术社区
原文链接:https://blog.csdn.net/2502_90288921/article/details/171159610



