三步流程

46.2 三步流程

下载 → 解析 → 存储,是几乎所有爬虫的骨架。

流程示意

# ========================================
# 示例:爬虫三步骨架
# 说明:伪代码展示流程
# ========================================
import requests
import re
import json

# 1. 下载
url = 'https://httpbin.org/html'
r = requests.get(url, timeout=10)
html = r.text

# 2. 解析(正则提取 h1 文字)
titles = re.findall(r'<h1>(.*?)</h1>', html)

# 3. 存储
with open('result.json', 'w', encoding='utf-8') as f:
    json.dump({'titles': titles}, f, ensure_ascii=False)
print('完成', titles)