爬虫(网络抓取)是 Python 最受欢迎的应用场景之一:把网页上的公开信息批量提取并保存为结构化数据。本文用一个真实例子,带你走完"请求页面 → 解析 HTML → 提取数据 → 保存结果"的完整流程。

1. 爬虫的基本流程

一个爬虫由三步组成:发送请求拿到 HTML → 解析定位目标数据 → 清洗保存。先看第一步:

import requests

url = "https://example.com/news"
resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
html = resp.text          # 页面源码
print(html[:200])         # 前 200 个字符

2. 安装 BeautifulSoup

解析 HTML 首选 beautifulsoup4,配合 lxml 解析器速度更快:

pip install beautifulsoup4 lxml

3. 解析与定位元素

CSS 选择器是定位元素最快的方式,select_one 取第一个,select 取全部:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "lxml")

# 取第一个标题
h1 = soup.select_one("h1").get_text(strip=True)

# 取所有文章标题
titles = [a.get_text(strip=True) for a in soup.select("article h2 a")]
print(titles)

4. 提取链接与属性

链接通常在 href 属性里,遇到相对路径要用 urljoin 拼成完整 URL:

from urllib.parse import urljoin

base = "https://example.com"
for a in soup.select("article a[href]"):
    href = a["href"]
    if href.startswith("/"):
        href = urljoin(base, href)   # 转成完整 URL
    print(href)

5. 保存为 CSV

把抓到的数据写入 CSV,后续统计和分析更方便:

import csv

rows = [{"title": t, "url": u} for t, u in zip(titles, urls)]
with open("news.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["title", "url"])
    writer.writeheader()
    writer.writerows(rows)

6. 反爬与爬虫礼仪

💡 学习建议:先用 requests + BeautifulSoup 抓一个静态新闻站练手,再进阶 Scrapy 框架与 Selenium 处理动态页面。只抓公开数据,尊重版权与 robots 协议。