Python 爬虫从入门到实战(一):基础篇——从零写出第一个爬虫

系列规划:

  • 第一篇(本篇):爬虫原理、HTTP 基础、requests 库、HTML 解析(BeautifulSoup / lxml+XPath / 正则 / JSON)、完整实战案例
  • 第二篇:进阶------请求头与反爬对抗、Cookie/Session、代理池、限速与重试、并发与异步(aiohttp)、动态页面(Selenium / Playwright)、抓包分析
  • 第三篇:工程化------数据存储(CSV/MySQL/MongoDB)、Scrapy 框架、增量爬取与去重、日志与异常、部署与调度、合规与 Robots 协议
  • 如三篇不足以讲完,将追加「扩展篇」:APP 抓包、JS 逆向入门、验证码识别、分布式爬虫等

一、爬虫到底是什么

爬虫(Web Crawler / Spider) 本质就是一个"自动访问网页并提取信息"的程序。你手动打开浏览器、复制粘贴数据的过程,交给代码自动完成,就是爬虫。

用一句话概括它的工作流程:

复制代码
发送 HTTP 请求  →  拿到响应(HTML/JSON/图片...)  →  解析提取数据  →  保存/继续跟进链接

爬虫能干的事很多:数据采集、价格监控、舆情分析、竞品调研、搜索引擎索引、自动化测试......但在动手之前,有一条底线必须先说清楚。

⚠️ 法律与道德边界(务必先读)

  1. 遵守 robots.txt :网站根目录下的 /robots.txt 声明了哪些路径允许抓取,用 https://域名/robots.txt 查看。
  2. 不爬取个人隐私、付费内容、需要登录的私密数据。
  3. 控制频率:不要给对方服务器造成压力,加延时、限并发。
  4. 遵守《网络安全法》《数据安全法》《个人信息保护法》 及网站用户协议。
  5. 遇到明确的技术保护措施(验证码、加密接口),不要绕过------这是很多司法案例的争议焦点。

本文所有示例均使用官方提供的爬虫练习站点 quotes.toscrape.com,完全合规。


二、HTTP 基础:爬虫的语言

爬虫和网站之间靠 HTTP 协议通信。你只要理解下面几个概念,就能看懂 90% 的爬虫代码。

2.1 请求方法

方法 用途 爬虫场景
GET 获取资源,参数拼在 URL 上 绝大多数页面抓取
POST 提交数据,参数在请求体里 登录、搜索、提交表单、调 API

2.2 URL 结构

复制代码
https://quotes.toscrape.com/tag/love/page/2/?sort=hot#top
└─┬─┘   └────────┬────────┘└─────┬──────┘└───┬───┘└─┬─┘└─┬─┘
 协议         域名(host)         路径 path   查询参数 query  锚点

注意:#top 这种锚点(fragment)不会发送给服务器,抓取时无意义。

2.3 常见状态码

状态码 含义 爬虫应对
200 成功 正常解析
301/302 重定向 requests 默认自动跟随
403 禁止访问 大概率被反爬,检查 headers
404 页面不存在 跳过
429 请求太频繁 降速、加延时(重要信号)
500/502/503 服务器错误 重试

2.4 请求头(Headers)------爬虫的第一道坎

服务器会看你"像不像浏览器"。最关键的几个头:

http 复制代码
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...   # 你是谁(浏览器标识)
Referer: https://example.com/list                            # 你从哪来
Cookie: sessionid=abc123                                     # 身份凭证
Accept-Language: zh-CN,zh;q=0.9                              # 语言偏好

不加 User-Agent 的 requests 请求,默认是 python-requests/x.x.x,等于自报家门"我是爬虫"。

2.5 响应内容类型

  • text/html:网页 → 用 HTML 解析器
  • application/json:接口数据 → 用 response.json()
  • image/jpeg、application/pdf 等二进制 → 用 response.content 存文件

三、环境准备

bash 复制代码
# 建议使用 Python 3.9+,并创建虚拟环境
python -m venv spider-env
# Windows
spider-env\Scripts\activate
# macOS / Linux
source spider-env/bin/activate

# 安装本篇文章需要的库
pip install requests beautifulsoup4 lxml
库 作用
requests 发送 HTTP 请求,最常用
beautifulsoup4 HTML/XML 解析,语法友好
lxml 高性能解析器,支持 XPath

四、requests 库详解

4.1 第一个请求

python 复制代码
import requests

url = "https://quotes.toscrape.com/"
resp = requests.get(url, timeout=10)

print(resp.status_code)      # 200
print(resp.encoding)         # 编码方式
print(resp.text[:300])       # 文本内容(前 300 字符)

4.2 GET 请求与参数

python 复制代码
# 方式一:直接拼 URL
requests.get("https://quotes.toscrape.com/tag/love/")

# 方式二:用 params 字典(推荐,会自动 URL 编码)
params = {"q": "python 爬虫", "page": 1}
resp = requests.get("https://httpbin.org/get", params=params)
print(resp.url)  # 看看最终拼成的 URL

4.3 POST 请求

python 复制代码
# 表单提交(application/x-www-form-urlencoded)
resp = requests.post("https://httpbin.org/post", data={"username": "demo", "password": "123"})

# JSON 提交(application/json)
resp = requests.post("https://httpbin.org/post", json={"keyword": "python"})

4.4 自定义请求头

python 复制代码
headers = {
    "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                   "AppleWebKit/537.36 (KHTML, like Gecko) "
                   "Chrome/122.0.0.0 Safari/537.36"),
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Referer": "https://quotes.toscrape.com/",
}

resp = requests.get("https://quotes.toscrape.com/", headers=headers, timeout=10)

4.5 编码问题(中文乱码必看)

python 复制代码
resp.encoding = "utf-8"          # 强制指定编码
text = resp.text                 # 再取文本

# 或者让 requests 猜(不一定准)
resp.encoding = resp.apparent_encoding

经验:优先看响应头 Content-Type 里的 charset,其次是网页 <meta charset="...">。国内老站点常见 gbk / gb2312。

4.6 二进制内容(图片/文件)

python 复制代码
resp = requests.get("https://quotes.toscrape.com/static/... .jpg", timeout=10)
with open("img.jpg", "wb") as f:
    f.write(resp.content)   # 注意是 content 不是 text
python 复制代码
s = requests.Session()          # 自动保持 Cookie
s.headers.update(headers)
s.get("https://quotes.toscrape.com/")
# 后续请求自动带上之前拿到的 Cookie

4.8 异常处理

python 复制代码
import requests
from requests.exceptions import RequestException

try:
    resp = requests.get(url, headers=headers, timeout=10)
    resp.raise_for_status()          # 4xx/5xx 抛异常
except RequestException as e:
    print("请求失败:", e)

timeout 一定要设! 否则一个卡死的请求能让整个脚本挂起。


五、HTML 解析:从页面里挖数据

拿到 HTML 后,要提取目标字段。常用四种方式,按推荐度排序:

方式 适用 优点 缺点
BeautifulSoup 通用 语法友好、容错强 稍慢
lxml + XPath 结构化页面 快、表达力强 语法需学习
正则 简单/非结构化文本 灵活 脆弱,HTML 一改就崩
JSON 接口 后台 API 最干净 需要会找接口

5.1 BeautifulSoup 基础

目标页面结构(quotes.toscrape.com 简化):

html 复制代码
<div class="quote">
    <span class="text">"The world as we have created it..."</span>
    <small class="author">Albert Einstein</small>
    <div class="tags">
        <a class="tag">change</a>
        <a class="tag">deep-thoughts</a>
    </div>
</div>
python 复制代码
from bs4 import BeautifulSoup

html = """(上面那段 HTML)"""
soup = BeautifulSoup(html, "lxml")      # 用 lxml 解析器,比默认快

# 1. 按标签+属性找
first = soup.find("div", class_="quote")

# 2. 按 CSS 选择器找所有(推荐)
quotes = soup.select("div.quote")
for q in quotes:
    text   = q.select_one("span.text").get_text(strip=True)
    author = q.select_one("small.author").get_text(strip=True)
    tags   = [t.get_text(strip=True) for t in q.select("a.tag")]
    print(text, "|", author, "|", tags)

常用方法速查:

python 复制代码
soup.find("a")                        # 第一个 <a>
soup.find("a", class_="tag")          # 带 class
soup.find("a", {"class": "tag"})      # 等价写法
soup.find_all("a", limit=5)           # 前 5 个
soup.select("div.quote a.tag")        # CSS 选择器
soup.select_one("span.text")
el.get_text(strip=True)               # 取纯文本并去空白
el["href"]                            # 取属性
el.get("href", "")                    # 取属性(带默认值,更安全)

⚠️ 注意 class_ 带下划线,因为 class 是 Python 关键字。

5.2 lxml + XPath

python 复制代码
from lxml import etree

tree = etree.HTML(html)
texts = tree.xpath('//div[@class="quote"]/span[@class="text"]/text()')
authors = tree.xpath('//div[@class="quote"]//small[@class="author"]/text()')
links = tree.xpath('//a[@class="tag"]/@href')     # 直接取属性

XPath 常用语法:

表达式 含义
//div 任意层级的 div
/div 直接子节点
//div[@class="quote"] 属性筛选
//div[contains(@class,"quo")] 属性包含
//a/text() 取文本
//a/@href 取属性
//div[1] 第一个
//div[last()] 最后一个

5.3 正则(兜底手段)

python 复制代码
import re

# 提取所有页码链接
pages = re.findall(r'href="(/page/\d+/)"', html)
# 提取某个数字字段
num = re.search(r'共\s*(\d+)\s*条', html)

原则:能用解析器就别用正则,正则适合从纯文本或 JSON 字符串里抠字段。

5.4 JSON 接口(最理想的情况)

很多现代网站数据是后台接口返回的 JSON,直接请求接口比解析 HTML 高效得多。

python 复制代码
resp = requests.get("https://httpbin.org/get", params={"a": 1})
data = resp.json()           # 直接转 dict
print(data["args"]["a"])

如何找接口? 打开浏览器 F12 → Network → 选 XHR/Fetch → 翻页/滚动观察新请求 → 看 Response 是不是结构化数据(第二篇会详细讲抓包)。


六、完整实战:抓取 quotes.toscrape.com 并翻页

目标:抓取全部页面的「名言 + 作者 + 标签」,并保存为 CSV。

python 复制代码
import csv
import time
import requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException

BASE_URL = "https://quotes.toscrape.com"
HEADERS = {
    "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                   "AppleWebKit/537.36 (KHTML, like Gecko) "
                   "Chrome/122.0.0.0 Safari/537.36"),
    "Accept-Language": "zh-CN,zh;q=0.9",
}


def parse_page(html: str):
    """解析单页,返回本页所有名言记录"""
    soup = BeautifulSoup(html, "lxml")
    records = []
    for q in soup.select("div.quote"):
        records.append({
            "text":   q.select_one("span.text").get_text(strip=True),
            "author": q.select_one("small.author").get_text(strip=True),
            "tags":   "|".join(t.get_text(strip=True) for t in q.select("a.tag")),
        })
    # 下一页链接(没有则返回 None)
    next_a = soup.select_one("li.next > a")
    next_url = BASE_URL + next_a["href"] if next_a else None
    return records, next_url


def crawl():
    all_records = []
    url, page = BASE_URL + "/", 1

    while url:
        print(f"正在抓取第 {page} 页:{url}")
        try:
            resp = requests.get(url, headers=HEADERS, timeout=10)
            resp.raise_for_status()
            resp.encoding = "utf-8"
        except RequestException as e:
            print(f"  请求失败,跳过:{e}")
            break

        records, url = parse_page(resp.text)
        all_records.extend(records)
        page += 1
        time.sleep(1)          # 礼貌延时,务必保留

    return all_records


if __name__ == "__main__":
    data = crawl()
    print(f"\n共抓取 {len(data)} 条记录")

    with open("quotes.csv", "w", newline="", encoding="utf-8-sig") as f:
        writer = csv.DictWriter(f, fieldnames=["text", "author", "tags"])
        writer.writeheader()
        writer.writerows(data)
    print("已保存到 quotes.csv")

这段代码覆盖了爬虫的完整骨架:

  1. 统一 headers(伪装成浏览器)
  2. timeout + raise_for_status() + try/except(健壮性)
  3. 解析出数据和「下一页地址」(翻页逻辑)
  4. time.sleep(1)(礼貌限速,避免 429)
  5. 循环直到没有下一页
  6. 保存为 utf-8-sig 编码的 CSV(Excel 打开不乱码)

七、新手最常踩的 6 个坑

现象 原因 解决
resp.text 中文乱码 编码识别错误 手动 resp.encoding = "utf-8" 或 "gbk"
状态码 403 无 UA / 被反爬 加完整 headers,见第二篇
抓到的是空壳 HTML 数据由 JS 渲染 用 Selenium/Playwright 或找后台接口(第二篇)
解析报 AttributeError: 'NoneType' select_one 没匹配到 加判空 if el: 或 el.get(...) 默认值
脚本卡死 没设 timeout 始终设 timeout=10
跑着跑着 429/封 IP 请求太快 time.sleep、限并发、用代理(第二篇)
CSV 用 Excel 打开乱码 编码问题 用 utf-8-sig

八、本篇小结 & 下一篇预告

你现在应该掌握:

  • ✅ 爬虫原理与合规底线
  • ✅ HTTP 请求方法、状态码、Headers、URL 结构
  • ✅ requests:GET/POST、headers、编码、二进制、Session、异常
  • ✅ 四种解析方式:BeautifulSoup、lxml+XPath、正则、JSON
  • ✅ 一个完整的「翻页 + 解析 + 存 CSV」爬虫

下一篇《进阶篇》将解决:

  1. 被反爬拦住怎么办:完整请求头、Referer 链、UA 池
  2. Cookie / Session 登录态模拟
  3. 代理 IP 与限速重试策略
  4. 并发爬虫:concurrent.futures 与异步 aiohttp
  5. 动态渲染页面:Selenium / Playwright 实操
  6. F12 抓包:如何找到隐藏的 JSON 接口

建议动手把第六节的代码跑通,并尝试改造:比如只抓取某个 tag(/tag/love/)下的内容,或把结果改成存进 JSON / SQLite。下一篇见。

相关推荐
无小道15 分钟前
Python语句的特色
python·语句
多加点辣也没关系1 小时前
JavaScript|第40章:JavaScript 工程化实践
开发语言·javascript·ecmascript
2601_967980111 小时前
python pytest如何编写测试
python·测试用例·pytest·函数·assert
2601_967980112 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块
大胖爱学习_MJ2 小时前
超越向量检索:用 Spring Boot + Neo4j 手搓 GraphRAG 知识图谱记忆
java·后端·python
RobinDevNotes3 小时前
24GB Mac 做数字人:声音放本地,画面租云端
人工智能·python·macos·开发工具
吃我一窝jio3 小时前
Java Bug复盘与性能优化实战
java·开发语言·笔记
学无止境小袁同学5 小时前
LlamaIndex Workflows 学习
python·llm·tensorflow·llamaindex·agent开发·多agent·workflows
Evand J5 小时前
【MATLAB例程】基于APF的多无人机动态路径规划与避障仿真。避碰及安全性能分析。附完整代码的下载链接
开发语言·matlab·无人机