想象你走进一家图书馆,想借一本《Python入门》。你需要先到前台登记(请求),馆员根据登记信息找到书(响应),最后把书交给你。HTTP协议就是爬虫与服务器之间的“对话规则”。
1.1 一次完整的HTTP请求流程
示例:用curl命令模拟请求
curl -X GET "https://example.com/api/books" \
-H "User-Agent: Mozilla/5.0" \
-H "Accept: application/json"
1.2 关键组件解析 请求方法:
状态码:
请求头:
响应头:
用Python写爬虫,核心是控制HTTP请求、解析响应数据、存储结果。
2.1 发送请求:从urllib到requests 原始方法:使用标准库urllib(复杂且易出错)
from urllib.request import urlopen, Request
req = Request("https://example.com", headers={"User-Agent": "Mozilla/5.0"})
response = urlopen(req)
print(response.read().decode("utf-8"))
推荐方法:第三方库requests(简洁强大)
import requests
response = requests.get("https://example.com", headers={"User-Agent": "Mozilla/5.0"})
print(response.text) # 自动解码为字符串
2.2 解析数据:HTML与JSON的“抽丝剥茧” HTML解析:BeautifulSoup或lxml
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
title = soup.find("h1").text # 提取标题
links = [a["href"] for a in soup.find_all("a")] # 提取所有链接
JSON处理:直接转为Python字典
import json
data = response.json() # 假设响应是JSON格式
print(data["books"][0]["title"])
2.3 存储数据:文件、数据库与CSV 保存到文件:
with open("output.html", "w", encoding="utf-8") as f:
f.write(response.text)
写入CSV:
import csv
with open("books.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["Title", "Author"])
for book in data["books"]:
writer.writerow([book["title"], book["author"]])
网站常通过IP限制、验证码、行为检测等手段阻止爬虫,需针对性破解。
3.1 IP封禁与代理池
解决方案: 使用代理IP(如requests配合proxies参数):
proxies = {"http": "http://123.123.123.123:8080"}
requests.get("https://example.com", proxies=proxies)
代理池工具:如scrapy-proxies或第三方服务(如站大爷)。 3.2 验证码识别
示例:用pytesseract识别简单验证码
import pytesseract
from PIL import Image
image = Image.open("captcha.png")
code = pytesseract.image_to_string(image)
print(code)
3.3 模拟浏览器行为
解决方案: Selenium:控制真实浏览器(Chrome/Firefox)。
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
element = driver.find_element_by_id("content")
print(element.text)
driver.quit()
Playwright:更现代的替代方案,支持无头模式。
目标:获取电影名称、评分、评价人数,保存为CSV。
4.1 分析页面结构
4.2 编写爬虫代码
import requests
from bs4 import BeautifulSoup
import csv
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
def scrape_douban_top250():
base_url = "https://movie.douban.com/top250"
movies = []
for start in range(0, 250, 25):
url = f"{base_url}?start={start}"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
for item in soup.find_all("div", class_="item"):
title = item.find("span", class_="title").text
rating = item.find("span", class_="rating_num").text
num_reviews = item.find("div", class_="star").find_all("span")[-1].text[:-3]
movies.append([title, rating, num_reviews])
return movies
# 保存数据
movies = scrape_douban_top250()
with open("douban_top250.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["标题", "评分", "评价人数"])
writer.writerows(movies)
4.3 优化与扩展
import time
import random
time.sleep(random.uniform(1, 3)) # 随机延迟1-3秒
多线程:用concurrent.futures加速爬取(需控制并发数)。
Q1:被网站封IP怎么办?
A:立即启用备用代理池,建议使用住宅代理(如站大爷IP代理),配合每请求更换IP策略。
Q2:爬虫需要学哪些Python库?
A:基础三件套:requests(发送HTTP请求)、BeautifulSoup(解析HTML)、re(正则匹配)。进阶可选Scrapy框架或Selenium模拟浏览器。
Q3:如何避免被反爬?
A:设置请求头(User-Agent)、控制请求频率(随机延迟)、使用会话(Session)保持Cookie,必要时模拟人类操作(如滚动页面)。
Q4:动态加载的数据怎么抓?
A:通过浏览器开发者工具分析XHR请求,直接抓取API接口;或用Selenium驱动真实浏览器渲染页面。
Q5:爬虫合法吗?
A:遵守目标网站的robots.txt协议,仅爬取公开数据,避免高频请求影响服务器,商用前需咨询法律意见。
Python爬虫的核心是理解HTTP协议、掌握请求与解析工具、应对反爬机制。从简单请求到模拟浏览器,从单页爬取到分布式架构,技术栈可逐步深化。未来,随着AI和自动化测试的发展,爬虫将更智能(如自动识别验证码、自适应反爬策略),但合法合规始终是第一原则。
进阶建议:
爬虫的世界充满挑战与乐趣,愿这份指南助你开启数据采集之旅!