4.3 Python 爬虫实战
爬虫基础原理
爬虫 = 自动化的网页数据采集程序
工作流程:
1. 发送 HTTP 请求 → 获取网页 HTML
2. 解析 HTML → 提取需要的数据
3. 数据清洗 → 格式化、去重
4. 保存数据 → 文件、数据库、API习惯把”目标数据长什么样""最终要存到哪里”先写在纸上或 Notion 里,这就是你的爬虫需求文档,丢给 AI 会准确很多。
为什么用 Python:
- ✅ 简单易学
- ✅ 生态丰富(requests、BeautifulSoup、Playwright)
- ✅ AI 擅长生成 Python 代码
法律和道德:
- ⚠️ 遵守 robots.txt
- ⚠️ 不要过于频繁请求(加延迟)
- ⚠️ 尊重网站的服务条款
- ⚠️ 不要爬取个人隐私数据
静态网页爬取(requests + BeautifulSoup)
适用场景:网页内容直接在 HTML 中(查看源代码能看到数据)
安装依赖
pip install requests beautifulsoup4基础示例:爬取博客文章
import requests
from bs4 import BeautifulSoup
# 1. 发送请求
url = "https://example.com/blog"
response = requests.get(url)
html = response.text
# 2. 解析 HTML
soup = BeautifulSoup(html, 'html.parser')
# 3. 提取数据
articles = soup.find_all('article', class_='post')
for article in articles:
title = article.find('h2').text.strip()
link = article.find('a')['href']
excerpt = article.find('p', class_='excerpt').text.strip()
print(f"标题: {title}")
print(f"链接: {link}")
print(f"摘要: {excerpt}")
print("---")调试爬虫时多打印几个字段(或写入日志),遇到结构变化也能第一时间排查。
用 AI 编写爬虫
第一步:分析网页结构
- 打开目标网页
- 右键 → 检查元素
- 找到包含数据的 HTML 元素
- 记录元素的标签、class、id
第二步:用 AI 生成爬虫代码
Prompt 模板:
帮我写一个 Python 爬虫,爬取以下网站:
https://example.com/blog
需要提取的数据:
- 文章标题(在 <h2 class="title"> 中)
- 文章链接(在 <a class="post-link"> 中)
- 发布日期(在 <time> 标签中)
- 文章摘要(在 <p class="excerpt"> 中)
要求:
1. 使用 requests 和 BeautifulSoup
2. 处理可能的错误(网络错误、元素不存在)
3. 添加 User-Agent 头
4. 在请求之间添加 1 秒延迟
5. 将数据保存为 JSON 文件
请生成完整的代码。动态网页爬取(Playwright)
适用场景:网页内容通过 JavaScript 动态加载(查看源代码看不到数据)
安装 Playwright
pip install playwright
playwright install基础示例
from playwright.sync_api import sync_playwright
def scrape_dynamic_page():
with sync_playwright() as p:
# 启动浏览器
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# 访问网页
page.goto("https://example.com")
# 等待内容加载
page.wait_for_selector('.article-list')
# 提取数据
articles = page.query_selector_all('.article')
for article in articles:
title = article.query_selector('h2').inner_text()
link = article.query_selector('a').get_attribute('href')
print(f"标题: {title}, 链接: {link}")
browser.close()
scrape_dynamic_page()Playwright 会真的打开一个无头浏览器,记得适当 wait_for_selector 或加 sleep,否则页面还没加载完就开始抓数据了。
实战案例:爬取博客文章
目标:爬取个人博客的所有文章并保存为 Markdown
完整代码示例:
import requests
from bs4 import BeautifulSoup
import time
import json
from pathlib import Path
def scrape_blog(base_url):
"""爬取博客文章"""
# 设置请求头(模拟浏览器)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
# 获取文章列表
response = requests.get(base_url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 找到所有文章链接
articles = soup.find_all('article', class_='post')
results = []
for idx, article in enumerate(articles):
try:
title = article.find('h2', class_='title').text.strip()
link = article.find('a')['href']
date = article.find('time')['datetime']
# 获取文章详情
article_response = requests.get(link, headers=headers)
article_soup = BeautifulSoup(article_response.text, 'html.parser')
# 提取正文
content = article_soup.find('div', class_='content').get_text(strip=True)
# 保存数据
article_data = {
'title': title,
'link': link,
'date': date,
'content': content
}
results.append(article_data)
# 保存为 Markdown
save_as_markdown(article_data, idx)
print(f"✓ 已爬取: {title}")
# 延迟,避免请求过快
time.sleep(1)
except Exception as e:
print(f"✗ 爬取失败: {e}")
continue
# 保存 JSON
with open('articles.json', 'w', encoding='utf-8') as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"\n完成!共爬取 {len(results)} 篇文章")
def save_as_markdown(article, idx):
"""保存为 Markdown 格式"""
filename = f"article_{idx+1}.md"
content = f"""# {article['title']}
发布日期: {article['date']}
原文链接: {article['link']}
---
{article['content']}
"""
Path('articles').mkdir(exist_ok=True)
with open(f"articles/{filename}", 'w', encoding='utf-8') as f:
f.write(content)
# 执行爬虫
if __name__ == "__main__":
scrape_blog("https://example.com/blog")上线跑批之前,最好先在 5-10 条数据上验证格式,再逐渐扩大范围,避免一次性爬几十页导致被封或存入错误数据。
用 AI 编写爬虫的完整流程
第一步:获取页面 HTML
在浏览器中:
- 打开目标网页
- 右键 → 检查元素
- 找到包含数据的 HTML 区块
- 右键该元素 → Copy → Copy outerHTML
第二步:给 AI 提供信息
Command + L
输入:
我想爬取这个网站的数据:https://example.com/blog
这是包含文章列表的 HTML 片段:
[粘贴你复制的 HTML]
请帮我:
1. 分析 HTML 结构
2. 编写爬虫代码提取以下信息:
- 文章标题
- 文章链接
- 发布日期
- 文章摘要
3. 保存为 JSON 格式
使用 Python + requests + BeautifulSoup第三步:测试和调试
# 先测试单个页面
def test_single_page():
url = "https://example.com/blog/first-post"
# ... 测试代码第四步:处理常见问题
| 问题 | 解决方案 |
|---|---|
| 请求被拒绝(403) | 添加 User-Agent 头 |
| 数据加载不出来 | 使用 Playwright(动态渲染) |
| 找不到元素 | 检查 HTML 结构是否正确 |
| 编码错误 | 指定 encoding=‘utf-8’ |
Last updated on