新三国小镇
55.33 MB · 2025-12-17
开发一个迷你爬虫,实现:
这是一个“只用 Python 标准库 + requests + BeautifulSoup”就能完成的轻量项目。
pip install requests beautifulsoup4 lxml
项目中需要用到:
推荐这样的结构:
mini_spider/
│── main.py # 主程序入口
│── fetcher.py # 网络请求模块
│── parser.py # 数据解析模块
│── saver.py # 文件保存模块
│── output/ # 保存爬取结果
这会让程序更像“可维护的小项目”,而不是零散脚本。
import requests
def fetch_html(url, timeout=10):
headers = {
"User-Agent": "Mozilla/5.0 (Mini Spider Project)"
}
try:
resp = requests.get(url, headers=headers, timeout=timeout)
resp.raise_for_status()
resp.encoding = resp.apparent_encoding
return resp.text
except requests.RequestException as e:
print(f"请求失败: {e}")
return None
功能亮点:
raise_for_status() 帮你捕获 404/500示例:提取文章标题、正文文本、所有超链接。
from bs4 import BeautifulSoup
def parse_page(html):
try:
soup = BeautifulSoup(html, "lxml")
title = soup.title.string if soup.title else "无标题"
# 提取正文
paragraphs = [p.get_text(strip=True) for p in soup.find_all("p")]
content = "n".join(paragraphs)
# 提取链接
links = [a['href'] for a in soup.find_all("a", href=True)]
return {
"title": title,
"content": content,
"links": links
}
except Exception as e:
print(f"解析失败: {e}")
return None
这个解析逻辑简单但通用,能适配大部分普通网页。
把爬取结果保存为 txt 文件。
import os
def save_result(data, filename="result.txt"):
if not os.path.exists("output"):
os.makedirs("output")
filepath = os.path.join("output", filename)
with open(filepath, "w", encoding="utf-8") as f:
f.write(f"标题:{data['title']}nn")
f.write("正文内容:n")
f.write(data["content"])
f.write("nn链接列表:n")
for link in data["links"]:
f.write(link + "n")
print(f"已保存到 {filepath}")
你也可以扩展成:
from fetcher import fetch_html
from parser import parse_page
from saver import save_result
def main():
url = input("请输入要爬取的URL:")
html = fetch_html(url)
if not html:
print("获取网页失败")
return
data = parse_page(html)
if not data:
print("解析失败")
return
save_result(data, filename="爬取结果.txt")
print("爬取完成!")
if __name__ == "__main__":
main()
运行效果:
请输入要爬取的URL:http://example.com
正在保存...
爬取完成!
这个“迷你爬虫项目”虽然简单,但框架很专业,因为它包含:
你稍微扩展一下就能变成:
批量 URL 爬虫 采集新闻网站文章 采集商品标题价格 监控网页变化 小规模数据采集脚本
如果你想进一步强化,可以加入:
从文件读取 URL 列表,一次抓一批。
降低被封风险。
提高稳定性。
方便后续分析。
变成真正的桌面工具。