requests + BeautifulSoup + os 爬虫三件套
发请求、解析页面、存文件——一套能跑通的 Python 爬虫流程,外加常见报错对照表。
爬虫的最小闭环就三步:把网页拿回来 → 从 HTML 里挑出数据 → 存到硬盘上。三个库正好一人管一段。
| 库 | 管什么 | 你主要用的东西 |
|---|---|---|
requests |
发 HTTP 请求,拿回网页源码 / JSON / 图片字节 | get、post、headers、params、timeout、session |
BeautifulSoup |
把 HTML 变成能按标签、class、CSS 选择器查找的树 | find、find_all、select、get_text |
os |
拼路径、建目录、列文件、读环境变量 | path.join、makedirs、listdir、walk、environ |
安装(lxml 是解析器,比内置的 html.parser 快很多):
python -m pip install requests beautifulsoup4 lxml
一、最小可用流程
import requests
from bs4 import BeautifulSoup
url = "https://quotes.toscrape.com/"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0 Safari/537.36"}
r = requests.get(url, headers=headers, timeout=10)
r.raise_for_status() # 4xx/5xx 直接抛异常,别让坏页面混进后面的解析
r.encoding = r.apparent_encoding # 防中文乱码
soup = BeautifulSoup(r.text, "lxml")
for q in soup.select("div.quote"):
print(q.select_one("span.text").get_text(strip=True))
二、requests:把网页拿回来
2.1 GET 与查询参数
params = {"q": "爬虫", "page": 2}
r = requests.get("https://example.com/search", params=params, timeout=10)
print(r.url) # https://example.com/search?q=%E7%88%AC%E8%99%AB&page=2
- 查询参数交给
params,别自己拼字符串——中文、空格、&它都会正确编码。 r.url是实际请求的地址,调试时先看它对不对。
2.2 headers 与 UA
requests 默认 UA 是 python-requests/2.x,很多站点一眼识别直接 403。至少要伪装 UA,必要时补 Referer、Cookie:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0 Safari/537.36",
"Referer": "https://example.com/list",
}
2.3 timeout 与异常处理
timeout 必须写,否则对方不响应时程序会一直挂着。
import time
for attempt in range(3):
try:
r = requests.get(url, headers=headers, timeout=10)
r.raise_for_status()
break
except requests.RequestException as e:
print("第", attempt + 1, "次失败:", e)
time.sleep(2)
else:
raise RuntimeError("重试三次仍失败")
requests.RequestException是这一族异常的总基类(连接失败、超时、重定向过多都算)。raise_for_status()只处理 4xx/5xx;网络层错误还是靠except。
2.4 响应体怎么取
| 属性 | 类型 | 用途 |
|---|---|---|
r.status_code |
int | 200 才是正常,其余先当失败处理 |
r.text |
str | 按 r.encoding 解码后的文本,给 BeautifulSoup 用 |
r.content |
bytes | 原始字节,下载图片、PDF、压缩包用这个 |
r.json() |
dict/list | 接口返回 JSON 时直接解析,失败会抛 JSONDecodeError |
r.headers |
dict-like | 看 Content-Type、Content-Length、Set-Cookie |
2.5 乱码的根因
requests 对 text/html 常按 ISO-8859-1 猜,中文站就花了。两种修法:
r.encoding = r.apparent_encoding # 让 chardet 猜,一般够用
# 或者明确指定
r.encoding = "utf-8"
2.6 POST:表单与 JSON
# 表单(Content-Type: application/x-www-form-urlencoded)
r = requests.post(url, data={"user": "a", "pwd": "b"}, timeout=10)
# JSON 接口(自动带 Content-Type: application/json)
r = requests.post(url, json={"name": "test"}, timeout=10)
data= 传字典就是表单;传字符串就是裸 body。json= 会自动序列化。
2.7 Session:保持登录态
s = requests.Session()
s.headers.update(headers)
s.post("https://example.com/login", data={"user": "a", "pwd": "b"}, timeout=10)
r = s.get("https://example.com/profile", timeout=10) # 自动带 Cookie
同一个 Session 里的 Cookie 会一直保留,也能复用连接,抓多页时更快。
2.8 下载图片 / 文件
r = requests.get(img_url, headers=headers, timeout=20)
with open("cover.jpg", "wb") as f: # 注意是 wb,不是 w
f.write(r.content)
三、BeautifulSoup:从 HTML 里挑数据
3.1 解析器
soup = BeautifulSoup(html, "lxml") # 快,需 pip 安装 lxml
soup = BeautifulSoup(html, "html.parser") # 内置,慢一点,够用
3.2 四种查找方式
soup.find("h1") # 第一个 h1,找不到返回 None
soup.find_all("a", class_="tag") # 所有 class 为 tag 的 a
soup.find("div", attrs={"data-id": "7"}) # 用属性精确匹配
soup.select("div.quote span.text") # CSS 选择器:后代
soup.select_one("ul.pager li.next a") # 只要第一个
soup.select("div.item > a") # 直接子元素
class_带下划线,因为class是 Python 关键字。select语法和浏览器 F12 里复制选择器一致,最省事。- 找不到就返回
None/ 空列表,不会报错,所以写if tag:判断,别直接.get_text()。
3.3 取值
tag.get_text(strip=True) # 取纯文本并去掉首尾空白(推荐)
tag.get_text(" ", strip=True) # 多个子节点之间用空格连接
tag["href"] # 取属性,属性不存在会 KeyError
tag.get("href") # 安全版,不存在返回 None
tag.name # 标签名
3.4 表格提取
rows = soup.select("table tbody tr")
for tr in rows:
cells = [td.get_text(strip=True) for td in tr.find_all("td")]
print(cells)
3.5 层级导航
tag.parent # 直接父节点
tag.find_parent("div") # 向上找第一个 div
tag.find_next_sibling("li") # 后一个兄弟
tag.find_all("a", recursive=False) # 只要直接子元素
抓「标题 + 作者 + 标签」这种组合数据时,通常先 select 到每个条目容器,再在容器里 select_one 各字段——比全局查找稳。
3.6 完整例子:抓一页 quotes
import requests
from bs4 import BeautifulSoup
def fetch_quotes(url):
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36"}
r = requests.get(url, headers=headers, timeout=10)
r.raise_for_status()
soup = BeautifulSoup(r.text, "lxml")
data = []
for box in soup.select("div.quote"):
text = box.select_one("span.text")
author = box.select_one("small.author")
tags = [a.get_text(strip=True) for a in box.select("div.tags a.tag")]
if text is None or author is None:
continue # 结构不全的条目跳过,别让一行坏数据毁掉整页
data.append({
"text": text.get_text(strip=True),
"author": author.get_text(strip=True),
"tags": ",".join(tags),
})
return data
print(fetch_quotes("https://quotes.toscrape.com/")[:2])
四、os:路径、目录、文件
4.1 拼路径不要用 +
import os
base = r"E:\Projects\code\crawl"
folder = os.path.join(base, "images") # 自动处理分隔符
print(os.path.basename("D:/a/b.txt")) # b.txt
print(os.path.dirname("D:/a/b.txt")) # D:/a
print(os.path.splitext("b.txt")) # ('b', '.txt')
4.2 建目录:存在也不报错
os.makedirs(folder, exist_ok=True) # 父目录一起建;exist_ok 避免目录已存在时报错
4.3 列目录、筛后缀
for name in os.listdir(folder):
if name.lower().endswith((".jpg", ".png")):
print(os.path.join(folder, name))
4.4 递归遍历整个目录
for root, dirs, files in os.walk(base):
for f in files:
path = os.path.join(root, f)
print(path)
4.5 判断存在
os.path.exists(path)
os.path.isfile(path)
os.path.isdir(path)
4.6 读环境变量(别把密钥写进代码)
token = os.environ.get("API_TOKEN") # 不存在返回 None
if token is None:
raise SystemExit("请先设置 API_TOKEN 环境变量")
4.7 文件名安全
网页标题里常有 \ / : * ? " < > |,Windows 下直接当文件名会失败:
import re
safe = re.sub(r'[\\/:*?"<>|]', "_", title)[:80]
4.8 顺便认识 pathlib
新代码更推荐 pathlib,读起来更顺:
from pathlib import Path
out = Path(r"E:\Projects\code\crawl") / "images"
out.mkdir(parents=True, exist_ok=True)
for p in out.glob("*.jpg"):
print(p.name, p.stat().st_size)
五、串起来:抓列表 + 存图 + 存 CSV
import csv
import os
import time
import re
import requests
from bs4 import BeautifulSoup
BASE = r"E:\Projects\code\crawl"
IMG_DIR = os.path.join(BASE, "images")
os.makedirs(IMG_DIR, exist_ok=True)
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36"}
def parse_page(html):
soup = BeautifulSoup(html, "lxml")
rows = []
for box in soup.select("div.quote"):
text = box.select_one("span.text")
author = box.select_one("small.author")
if not text or not author:
continue
rows.append({
"text": text.get_text(strip=True),
"author": author.get_text(strip=True),
})
return rows
all_rows = []
for page in range(1, 4): # 抓前 3 页
url = f"https://quotes.toscrape.com/page/{page}/"
r = requests.get(url, headers=HEADERS, timeout=10)
if r.status_code != 200:
print("跳过", url, r.status_code)
continue
all_rows.extend(parse_page(r.text))
time.sleep(1) # 限速,别把人家站点打崩
csv_path = os.path.join(BASE, "quotes.csv")
with open(csv_path, "w", newline="", encoding="utf-8-sig") as f: # utf-8-sig 让 Excel 不乱码
writer = csv.DictWriter(f, fieldnames=["text", "author"])
writer.writeheader()
writer.writerows(all_rows)
print("共", len(all_rows), "条 →", csv_path)
要点:
csv.DictWriter的fieldnames要和字典的键一致。- 写中文 CSV 用
encoding="utf-8-sig",Excel 双击打开才不乱码。 - 循环里
time.sleep(1),既是礼貌也是避免被封。
六、常见报错对照表
| 现象 | 大概率原因 | 处理 |
|---|---|---|
403 Forbidden / 418 |
UA 被识别、缺 Cookie/Referer、触发风控 | 补 headers、降频、换 IP 段;仍不行说明有反爬,别硬刚 |
404 Not Found |
URL 写错、分页超出范围 | 打印 r.url 核对 |
中文全是 æ–‡ 之类 |
编码猜错 | r.encoding = r.apparent_encoding |
AttributeError: 'NoneType' object has no attribute 'get_text' |
find / select_one 没匹配到 |
先 if tag: 再取值 |
requests.exceptions.ConnectTimeout |
网络不通或对方太慢 | 检查代理、加 timeout、重试 |
SSLError |
证书问题 / 公司代理 | 升级 certifi,别轻易 verify=False |
UnicodeEncodeError |
写文件没指定编码 | open(..., encoding="utf-8") |
select 返回空列表 |
class 拼错,或内容是 JS 动态渲染 | 对比浏览器「查看网页源代码」,动态页改用接口/Playwright |
| 解析出重复数据 | 选择器范围太大 | 先定位条目容器,再在容器内取字段 |
七、合规与礼貌
- 先看
https://站点/robots.txt,Disallow的路径别抓。 - 控制频率(每次请求间隔 1–2 秒),别并发几百个请求把人家站点打挂。
- 不抓个人隐私、付费内容、登录后的数据。
- 抓下来的数据自己分析可以,整站转载要授权。
八、速查表
# requests
r = requests.get(url, params={...}, headers={...}, timeout=10)
r.raise_for_status()
r.encoding = r.apparent_encoding
r.text / r.content / r.json() / r.status_code
requests.post(url, data={...}) # 表单
requests.post(url, json={...}) # JSON
s = requests.Session() # 保持 Cookie
# BeautifulSoup
soup = BeautifulSoup(html, "lxml")
soup.find("div", class_="x")
soup.select("div.item span.text")
tag.get_text(strip=True)
tag.get("href")
# os
os.path.join(base, name)
os.makedirs(path, exist_ok=True)
os.listdir(dir) / os.walk(dir)
os.path.exists(p)
os.environ.get("KEY")
open(path, "w", encoding="utf-8-sig") # 中文 CSV 给 Excel
九、可直接套用的模板
下面四段都是完整能跑的骨架:把配置区的 URL、选择器、保存路径改掉,就是你要的爬虫。写新脚本时直接复制,不要从零敲。
模板 1:单页抓取(请求 → 解析 → 存 CSV)
import csv
import os
import time
import requests
from bs4 import BeautifulSoup
CONFIG = {
"url": "https://quotes.toscrape.com/",
"headers": {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36"},
"csv_path": r"E:\Projects\code\crawl\data.csv",
"timeout": 10,
}
def fetch(url, headers, timeout=10, retries=3):
"""带重试的 GET,失败返回 None。"""
for i in range(retries):
try:
r = requests.get(url, headers=headers, timeout=timeout)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except requests.RequestException as e:
print(f"[{i + 1}/{retries}] 请求失败: {e}")
time.sleep(2 * (i + 1)) # 退避,越错等越久
return None
def parse(html):
"""改这里:选择器换成目标页面的结构。"""
soup = BeautifulSoup(html, "lxml")
rows = []
for box in soup.select("div.quote"):
text = box.select_one("span.text")
author = box.select_one("small.author")
if not text or not author: # 结构不全的条目跳过
continue
rows.append({
"text": text.get_text(strip=True),
"author": author.get_text(strip=True),
})
return rows
def save_csv(rows, path):
if not rows:
print("没有数据,不写文件")
return
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
writer.writeheader()
writer.writerows(rows)
print(f"写入 {len(rows)} 行 → {path}")
if __name__ == "__main__":
html = fetch(CONFIG["url"], CONFIG["headers"], CONFIG["timeout"])
if html:
save_csv(parse(html), CONFIG["csv_path"])
模板 2:分页抓取(重试 + 限速 + 去重 + 自动停)
import time
import requests
from bs4 import BeautifulSoup
# 把模板 1 里的 fetch() 和 save_csv() 两个函数直接贴到这个文件顶部
BASE = "https://quotes.toscrape.com/page/{}/"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36"}
DELAY = 1.0 # 每次请求间隔,秒
MAX_PAGES = 50 # 兜底上限,防止死循环
OUT = r"E:\Projects\code\crawl\all_pages.csv"
def parse(html):
soup = BeautifulSoup(html, "lxml")
rows = []
for box in soup.select("div.quote"):
text = box.select_one("span.text")
author = box.select_one("small.author")
if text and author:
rows.append({
"text": text.get_text(strip=True),
"author": author.get_text(strip=True),
})
return rows
def main():
seen, all_rows = set(), []
empty_pages = 0
for page in range(1, MAX_PAGES + 1):
html = fetch(BASE.format(page), HEADERS)
if html is None:
print(f"第 {page} 页请求失败,停止")
break
rows = parse(html)
new_rows = [r for r in rows if r["text"] not in seen]
for r in new_rows:
seen.add(r["text"])
if not new_rows:
empty_pages += 1
if empty_pages >= 2: # 连续两页没有新数据 → 说明到最后一页了
print(f"第 {page} 页无新数据,停止")
break
else:
empty_pages = 0
all_rows.extend(new_rows)
print(f"第 {page} 页 +{len(new_rows)} 条,累计 {len(all_rows)}")
time.sleep(DELAY)
save_csv(all_rows, OUT)
if __name__ == "__main__":
main()
翻页地址不止 page/{} 一种,常见还有:
?page=2→ 用requests.get(url, params={"page": page})- 下一页链接在 HTML 里 →
soup.select_one("a.next")["href"],配合urljoin(BASE, href)拼绝对地址
模板 3:图片 / 文件批量下载(断点续抓)
import os
import re
import time
import requests
OUT_DIR = r"E:\Projects\code\crawl\images"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36"}
# 换成你的图片地址列表,或从 CSV 里读一列
IMAGE_URLS = [
"https://quotes.toscrape.com/static/1.jpg",
]
def safe_name(name, fallback="img"):
"""去掉 Windows 不允许的字符,并限制长度。"""
name = re.sub(r'[\\/:*?"<>|]', "_", name).strip()
return (name[:80] or fallback)
def download(url, index, out_dir=OUT_DIR):
os.makedirs(out_dir, exist_ok=True)
ext = os.path.splitext(url.split("?")[0])[1] or ".jpg"
path = os.path.join(out_dir, f"{index:04d}_{safe_name(os.path.basename(url).split('.')[0])}{ext}")
if os.path.exists(path) and os.path.getsize(path) > 0:
print("已存在,跳过", path) # 断点续抓:重跑不会重复下载
return path
try:
r = requests.get(url, headers=HEADERS, timeout=20, stream=True)
r.raise_for_status()
with open(path, "wb") as f:
for chunk in r.iter_content(8192):
f.write(chunk)
print("下载完成", path)
return path
except requests.RequestException as e:
print("下载失败", url, e)
return None
if __name__ == "__main__":
for i, url in enumerate(IMAGE_URLS, 1):
download(url, i)
time.sleep(1)
stream=True+iter_content适合大文件,不会一次把几百 MB 读进内存。- 文件名用序号打头(
0001_xxx.jpg),排序稳定,也避免重名覆盖。
模板 4:HTML 表格 → CSV
import csv
import requests
from bs4 import BeautifulSoup
URL = "https://example.com/table-page"
OUT = r"E:\Projects\code\crawl\table.csv"
def table_to_rows(html, index=0):
soup = BeautifulSoup(html, "lxml")
tables = soup.find_all("table")
if not tables:
return []
table = tables[index]
headers = [th.get_text(strip=True) for th in table.find_all("th")]
rows = []
for tr in table.find_all("tr"):
tds = tr.find_all("td")
if not tds:
continue
cells = [td.get_text(strip=True) for td in tds]
if headers and len(cells) == len(headers):
rows.append(dict(zip(headers, cells)))
else:
rows.append({f"c{i}": v for i, v in enumerate(cells)})
return rows
if __name__ == "__main__":
r = requests.get(URL, timeout=10)
r.raise_for_status()
r.encoding = r.apparent_encoding
rows = table_to_rows(r.text)
if rows:
with open(OUT, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
writer.writeheader()
writer.writerows(rows)
print("写入", len(rows), "行 →", OUT)
套用顺序(别一上来就抓全站)
- 先只抓一页,把
print打出来看字段对不对、选择器有没有命中; - 确认标题、链接、时间都在,再存 CSV;
- 存对了再打开分页循环,
DELAY从 1 秒起步,看对方站点反应; - 要下载图片/附件时再套模板 3,重跑一次验证「跳过已存在」生效;
- 数据量上来后,把
seen换成数据库或去重列(比如按 URL 唯一),避免内存越跑越大。