在掌握了基本的爬虫流程之后,是时候进入实战阶段了。本文将带你通过几个真实网站的数据抓取示例,掌握常见的数据结构解析方法、反爬机制应对策略以及如何将爬取的数据结构化存储。


一、准备工作

1. 使用的技术栈

  • requests:发送HTTP请求
  • BeautifulSoup / lxml:HTML解析
  • pandas / csv:数据存储
  • fake_useragent(可选):防止被封IP

安装命令:

pip install requests beautifulsoup4 lxml pandas fake-useragent

二、实战一:抓取知乎热榜

目标网址:

https://www.zhihu.com/hot

知乎热榜是一个动态页面,前端使用 JavaScript 渲染,但其热榜数据实际来自于接口,我们可以直接请求接口来获取 JSON 数据。

抓取思路:

  1. 打开知乎热榜页面,使用浏览器 F12 → Network → XHR 查看请求
  2. 找到热榜接口:https://www.zhihu.com/api/v3/feed/topstory/hot-list
  3. 请求这个接口并解析 JSON 返回内容

示例代码:

import requests
import pandas as pd

headers = {
    "User-Agent": "Mozilla/5.0",
    "Referer": "https://www.zhihu.com/"
}

url = "https://www.zhihu.com/api/v3/feed/topstory/hot-list"

response = requests.get(url, headers=headers)
data = response.json()

hot_list = []
for item in data["data"]:
    title = item["target"]["title"]
    excerpt = item["target"].get("excerpt", "")
    link = "https://www.zhihu.com/question/" + item["target"]["id"]
    hot_list.append([title, excerpt, link])

# 保存为 CSV
df = pd.DataFrame(hot_list, columns=["标题", "摘要", "链接"])
df.to_csv("知乎热榜.csv", index=False, encoding="utf-8-sig")

三、实战二:爬取虎嗅网热门文章

目标网址:

https://www.huxiu.com/article

虎嗅的首页是动态加载文章列表的,但文章详情页是静态的,可以直接抓取。

实现步骤:

  1. 先访问首页,获取文章链接
  2. 访问每篇文章详情页,解析标题和正文内容

示例代码:

import requests
from bs4 import BeautifulSoup
import time

headers = {
    "User-Agent": "Mozilla/5.0"
}
base_url = "https://www.huxiu.com"

response = requests.get(base_url + "/article", headers=headers)
soup = BeautifulSoup(response.text, "lxml")

links = soup.select("a.title")[:10]  # 取前10篇

articles = []
for link in links:
    href = base_url + link["href"]
    article_resp = requests.get(href, headers=headers)
    article_soup = BeautifulSoup(article_resp.text, "lxml")
    title = article_soup.find("h1", class_="article__title").text.strip()
    content_div = article_soup.find("div", class_="article-content-wrap")
    paragraphs = content_div.find_all("p")
    content = "\n".join([p.text for p in paragraphs])
    articles.append([title, href, content])
    time.sleep(1)  # 避免访问过快被封

# 存储
df = pd.DataFrame(articles, columns=["标题", "链接", "正文"])
df.to_csv("虎嗅热门文章.csv", index=False, encoding="utf-8-sig")

四、反爬机制应对小技巧

反爬方式应对策略
User-Agent 限制使用随机 UA,如 fake_useragent
IP 封锁使用代理 IP 池
请求频率限制增加 time.sleep(),模拟人类行为
Cookie 校验使用浏览器登录后复制 Cookie 或用 requests.Session()
JavaScript 渲染使用 Selenium 或分析接口(如知乎示例)

五、进阶建议

  • 使用 Scrapy 构建大型项目,支持自动限速、去重、管道处理
  • 结合数据库如 MongoDB / MySQL 存储结构化数据
  • 用 Flask / FastAPI 构建爬虫数据可视化平台

六、结语

实战是学习爬虫的最好方式。通过对热门网站(如知乎、虎嗅)的数据抓取,不仅能提升技术能力,还能获取有价值的内容做数据分析、机器学习训练等用途。后续我将分享更多爬虫+AI应用的项目,如“基于爬虫的情感分析”、“短视频评论抓取分析”等,欢迎关注!

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐