人工智能之编程进阶 Python高级
第九章 爬虫类模块
文章目录
- [人工智能之编程进阶 Python高级](#人工智能之编程进阶 Python高级)
- 前言
- [🌐 一、`urllib` ------ Python 标准库的 HTTP 客户端](#🌐 一、
urllib—— Python 标准库的 HTTP 客户端)
- [✅ 定位](#✅ 定位)
- [🔧 模块组成](#🔧 模块组成)
- [💡 基本用法](#💡 基本用法)
- [1. GET 请求](#1. GET 请求)
- [2. POST 请求(带参数)](#2. POST 请求(带参数))
- [3. 添加请求头(模拟浏览器)](#3. 添加请求头(模拟浏览器))
- [4. URL 编码/解码](#4. URL 编码/解码)
- [⚠️ 缺点](#⚠️ 缺点)
- [✅ 适用场景](#✅ 适用场景)
- [🚀 二、`requests` ------ 最流行的 HTTP 库](#🚀 二、
requests—— 最流行的 HTTP 库)
- [✅ 定位](#✅ 定位)
- [🔧 安装](#🔧 安装)
- [💡 基本用法](#💡 基本用法)
- [1. GET / POST](#1. GET / POST)
- [2. 请求头 & 超时](#2. 请求头 & 超时)
- [3. 会话(自动管理 Cookie)](#3. 会话(自动管理 Cookie))
- [4. 文件上传 / 下载](#4. 文件上传 / 下载)
- [5. 异常处理](#5. 异常处理)
- [✅ 高级功能](#✅ 高级功能)
- [✅ 适用场景](#✅ 适用场景)
- [🕵️ 三、`selenium` ------ 浏览器自动化神器](#🕵️ 三、
selenium—— 浏览器自动化神器)
- [✅ 定位](#✅ 定位)
- [🔧 安装](#🔧 安装)
- [💡 基本用法](#💡 基本用法)
- [1. 启动浏览器(自动管理驱动)](#1. 启动浏览器(自动管理驱动))
- [2. 等待元素加载(关键!)](#2. 等待元素加载(关键!))
- [3. 模拟用户操作](#3. 模拟用户操作)
- [4. 获取渲染后的 HTML](#4. 获取渲染后的 HTML)
- [5. 无头模式(后台运行)](#5. 无头模式(后台运行))
- [⚠️ 缺点](#⚠️ 缺点)
- [✅ 适用场景](#✅ 适用场景)
- [🧼 四、`BeautifulSoup` ------ HTML/XML 解析利器](#🧼 四、
BeautifulSoup—— HTML/XML 解析利器)
- [✅ 定位](#✅ 定位)
- [🔧 安装](#🔧 安装)
- [💡 基本用法](#💡 基本用法)
- [1. 创建解析对象](#1. 创建解析对象)
- [2. 查找元素](#2. 查找元素)
- [3. 提取属性与文本](#3. 提取属性与文本)
- [4. 与 requests/selenium 结合](#4. 与 requests/selenium 结合)
- [✅ 优势](#✅ 优势)
- [✅ 适用场景](#✅ 适用场景)
- [🕷️ 五、`Scrapy` ------ 专业级爬虫框架](#🕷️ 五、
Scrapy—— 专业级爬虫框架)
- [✅ 定位](#✅ 定位)
- [🔧 安装](#🔧 安装)
- [💡 基本项目结构](#💡 基本项目结构)
- [💡 核心组件示例](#💡 核心组件示例)
- [1. 定义 Item(数据模型)](#1. 定义 Item(数据模型))
- [2. 编写 Spider](#2. 编写 Spider)
- [3. 数据管道(存入 JSON/数据库)](#3. 数据管道(存入 JSON/数据库))
- [4. 启动爬虫](#4. 启动爬虫)
- [✅ 高级特性](#✅ 高级特性)
- [⚠️ 缺点](#⚠️ 缺点)
- [✅ 适用场景](#✅ 适用场景)
- [🔍 六、五大工具全景对比](#🔍 六、五大工具全景对比)
- [✅ 七、选型建议(一句话总结)](#✅ 七、选型建议(一句话总结))
- [🛡️ 八、法律与道德提醒](#🛡️ 八、法律与道德提醒)
- 资料关注
前言
本文主要叙述网路数据获取以及网页解析相关的模块,掌握此模块有利于在相关网页获取有价值的信息。主要包括以下几个模块:
urllib(标准库)requests(第三方,最流行)selenium(浏览器自动化)BeautifulSoup(HTML/XML 解析)Scrapy(专业爬虫框架)
🌐 一、urllib ------ Python 标准库的 HTTP 客户端
✅ 定位
Python 内置模块,无需安装,适合轻量级 HTTP 请求或学习底层原理。
🔧 模块组成
urllib.request:打开 URL(GET/POST)urllib.parse:URL 编码/解析urllib.error:处理异常urllib.robotparser:解析 robots.txt
💡 基本用法
1. GET 请求
python
from urllib import request
url = "https://httpbin.org/get"
with request.urlopen(url) as resp:
data = resp.read().decode('utf-8')
print(data)
2. POST 请求(带参数)
python
from urllib import request, parse
url = "https://httpbin.org/post"
data = parse.urlencode({'name': 'Alice', 'age': 30}).encode()
req = request.Request(url, data=data)
with request.urlopen(req) as resp:
print(resp.read().decode())
3. 添加请求头(模拟浏览器)
python
headers = {'User-Agent': 'Mozilla/5.0'}
req = request.Request(url, headers=headers)
resp = request.urlopen(req)
4. URL 编码/解码
python
from urllib.parse import urlencode, urlparse, parse_qs
# 编码
params = {'q': '中文', 'page': 1}
encoded = urlencode(params) # q=%E4%B8%AD%E6%96%87&page=1
# 解析 URL
parsed = urlparse("https://example.com/path?k=v")
print(parsed.query) # k=v
print(parse_qs(parsed.query)) # {'k': ['v']}
⚠️ 缺点
- API 繁琐(需手动 encode、构造 Request 对象)
- 不支持会话(Session)、Cookie 自动管理
- 错误处理复杂
✅ 适用场景
- 不能安装第三方库的环境(如某些服务器)
- 学习 HTTP 原理
- 简单脚本(如下载文件)
🚀 二、requests ------ 最流行的 HTTP 库
✅ 定位
"人类友好的 HTTP 库",简洁、强大、社区广泛,是绝大多数项目的首选。
🔧 安装
bash
pip install requests
💡 基本用法
1. GET / POST
python
import requests
# GET
resp = requests.get("https://httpbin.org/get", params={'q': 'python'})
print(resp.status_code, resp.json())
# POST
resp = requests.post("https://httpbin.org/post", data={'name': 'Bob'})
print(resp.json())
2. 请求头 & 超时
python
headers = {'User-Agent': 'MyBot/1.0'}
resp = requests.get(url, headers=headers, timeout=5)
3. 会话(自动管理 Cookie)
python
session = requests.Session()
session.headers.update({'User-Agent': 'MyApp'})
# 登录后自动携带 Cookie
session.post(login_url, data=login_data)
profile = session.get(profile_url) # 已登录状态
4. 文件上传 / 下载
python
# 上传文件
with open('photo.jpg', 'rb') as f:
requests.post(upload_url, files={'file': f})
# 下载大文件(流式)
with requests.get(file_url, stream=True) as r:
with open('large.zip', 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
5. 异常处理
python
try:
resp = requests.get(url, timeout=3)
resp.raise_for_status() # 非 2xx 抛出异常
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.HTTPError as e:
print("HTTP错误:", e)
✅ 高级功能
- 支持代理:
proxies={'http': 'http://10.10.1.10:3128'} - SSL 验证控制:
verify=False(不推荐生产用) - 重定向控制:
allow_redirects=False - PreparedRequest:预构建请求(用于调试/复用)
✅ 适用场景
- API 调用(RESTful)
- 简单网页抓取(静态内容)
- 自动化测试
- 数据采集脚本
🕵️ 三、selenium ------ 浏览器自动化神器
✅ 定位
控制真实浏览器(Chrome/Firefox),能执行 JavaScript、处理动态渲染页面(如 React/Vue 单页应用)。
🔧 安装
bash
pip install selenium
# 并下载对应浏览器驱动(如 chromedriver)
# 推荐使用 webdriver-manager 自动管理:
pip install webdriver-manager
💡 基本用法
1. 启动浏览器(自动管理驱动)
python
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://example.com")
# 查找元素
title = driver.find_element(By.TAG_NAME, "h1").text
print(title)
driver.quit()
2. 等待元素加载(关键!)
python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, "dynamic-content")))
3. 模拟用户操作
python
# 点击
button = driver.find_element(By.ID, "submit")
button.click()
# 输入文本
search_box = driver.find_element(By.NAME, "q")
search_box.send_keys("Python爬虫")
search_box.submit()
# 执行 JS
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
4. 获取渲染后的 HTML
python
html = driver.page_source # 包含 JS 执行后的完整 DOM
5. 无头模式(后台运行)
python
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless") # 无界面
driver = webdriver.Chrome(options=options)
⚠️ 缺点
- 速度慢(启动浏览器开销大)
- 资源占用高(每个实例占几百 MB 内存)
- 维护成本高(需匹配浏览器与驱动版本)
✅ 适用场景
- 动态网页(内容由 JS 加载)
- 需要登录/验证码/滑块验证的网站
- 自动化测试(UI 测试)
- 模拟真实用户行为(如点击、滚动)
🧼 四、BeautifulSoup ------ HTML/XML 解析利器
✅ 定位
不是网络请求库! 专门用于解析 HTML/XML 文档,提取结构化数据。
🔧 安装
bash
pip install beautifulsoup4
# 推荐搭配解析器 lxml(更快更容错):
pip install lxml
💡 基本用法
1. 创建解析对象
python
from bs4 import BeautifulSoup
html = """
<html>
<body>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<a href="/page2">Next</a>
</body>
</html>
"""
soup = BeautifulSoup(html, 'lxml') # 或 'html.parser'
2. 查找元素
python
# find / find_all
divs = soup.find_all('div', class_='item')
for div in divs:
print(div.text) # Item 1, Item 2
# CSS 选择器(推荐)
items = soup.select('div.item')
link = soup.select_one('a[href]')['href'] # /page2
3. 提取属性与文本
python
tag = soup.div
print(tag.get_text()) # Item 1
print(tag['class']) # ['item']
print(tag.attrs) # {'class': ['item']}
4. 与 requests/selenium 结合
python
# 从 requests 获取 HTML
resp = requests.get(url)
soup = BeautifulSoup(resp.text, 'lxml')
# 从 selenium 获取 HTML
soup = BeautifulSoup(driver.page_source, 'lxml')
✅ 优势
- 语法简洁直观(尤其 CSS 选择器)
- 容错性强(能解析不规范 HTML)
- 支持多种解析器(html.parser, lxml, html5lib)
✅ 适用场景
- 从 HTML 中提取标题、链接、表格等
- 数据清洗与结构化
- 配合 requests/selenium 使用
🕷️ 五、Scrapy ------ 专业级爬虫框架
✅ 定位
全功能爬虫框架,支持并发、去重、中间件、管道、分布式等企业级特性。
🔧 安装
bash
pip install scrapy
💡 基本项目结构
bash
scrapy startproject myspider
cd myspider
scrapy genspider quotes quotes.toscrape.com
生成目录:
myspider/
├── scrapy.cfg
└── myspider/
├── __init__.py
├── items.py # 定义数据结构
├── middlewares.py # 中间件(请求/响应处理)
├── pipelines.py # 数据处理管道(存数据库等)
├── settings.py # 配置(UA、并发数、延迟等)
└── spiders/
└── quotes.py # 爬虫逻辑
💡 核心组件示例
1. 定义 Item(数据模型)
python
# items.py
import scrapy
class QuoteItem(scrapy.Item):
text = scrapy.Field()
author = scrapy.Field()
tags = scrapy.Field()
2. 编写 Spider
python
# spiders/quotes.py
import scrapy
from myspider.items import QuoteItem
class QuotesSpider(scrapy.Spider):
name = 'quotes'
start_urls = ['http://quotes.toscrape.com']
def parse(self, response):
for quote in response.css('div.quote'):
item = QuoteItem()
item['text'] = quote.css('span.text::text').get()
item['author'] = quote.css('small.author::text').get()
item['tags'] = quote.css('a.tag::text').getall()
yield item
# 翻页
next_page = response.css('li.next a::attr(href)').get()
if next_page:
yield response.follow(next_page, self.parse)
3. 数据管道(存入 JSON/数据库)
python
# pipelines.py
class JsonWriterPipeline:
def open_spider(self, spider):
self.file = open('quotes.json', 'w')
def close_spider(self, spider):
self.file.close()
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
4. 启动爬虫
bash
scrapy crawl quotes
# 输出到 JSON
scrapy crawl quotes -o quotes.json
✅ 高级特性
- 自动限速 :
AUTOTHROTTLE_ENABLED = True - User-Agent 轮换:通过中间件
- 去重:内置 Request 去重(基于指纹)
- 并发控制 :
CONCURRENT_REQUESTS = 16 - 中间件:修改请求/响应(如加代理、处理 Cookies)
- 扩展性强:支持 Redis 分布式(Scrapy-Redis)
⚠️ 缺点
- 学习曲线陡峭
- 不适合简单脚本(杀鸡用牛刀)
- 动态页面需结合 Selenium(通过
scrapy-selenium插件)
✅ 适用场景
- 大规模数据采集(万级页面)
- 需要长期维护的爬虫项目
- 企业级数据抓取系统
🔍 六、五大工具全景对比
| 工具 | 类型 | 是否发请求 | 是否解析 HTML | 是否执行 JS | 适用场景 |
|---|---|---|---|---|---|
urllib |
标准库 HTTP 客户端 | ✅ | ❌ | ❌ | 简单请求、教学 |
requests |
第三方 HTTP 库 | ✅ | ❌ | ❌ | API 调用、静态页抓取 |
selenium |
浏览器自动化 | ✅(通过浏览器) | ❌(需配合解析器) | ✅ | 动态页、登录、JS 渲染 |
BeautifulSoup |
HTML 解析器 | ❌ | ✅ | ❌ | 数据提取、清洗 |
Scrapy |
爬虫框架 | ✅ | ✅(内置 Selector) | ❌(需插件) | 大规模、结构化爬虫 |
💡 典型组合:
- 静态页面:
requests + BeautifulSoup- 动态页面:
selenium + BeautifulSoup- 大型项目:
Scrapy(可集成selenium处理动态内容)
✅ 七、选型建议(一句话总结)
- 只想发个 HTTP 请求? → 用
requests(除非不能装第三方,才用urllib) - 页面内容是 JS 动态加载的? → 用
selenium - 从 HTML 里抽数据? → 用
BeautifulSoup(或 Scrapy 的response.css()/xpath()) - 要爬几万个页面,还要去重、存数据库、自动重试? → 用
Scrapy
🛡️ 八、法律与道德提醒
- 遵守
robots.txt(可用urllib.robotparser解析) - 控制请求频率(避免 DDoS)
- 不要爬取隐私/付费/敏感数据
- 尊重网站版权与服务条款
🌐 合法合规,才是长久之道。
资料关注
公众号:咚咚王
《Python编程:从入门到实践》
《利用Python进行数据分析》
《算法导论中文第三版》
《概率论与数理统计(第四版) (盛骤) 》
《程序员的数学》
《线性代数应该这样学第3版》
《微积分和数学分析引论》
《(西瓜书)周志华-机器学习》
《TensorFlow机器学习实战指南》
《Sklearn与TensorFlow机器学习实用指南》
《模式识别(第四版)》
《深度学习 deep learning》伊恩·古德费洛著 花书
《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》
《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen) 》
《自然语言处理综论 第2版》
《Natural-Language-Processing-with-PyTorch》
《计算机视觉-算法与应用(中文版)》
《Learning OpenCV 4》
《AIGC:智能创作时代》杜雨+&+张孜铭
《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》
《从零构建大语言模型(中文版)》
《实战AI大模型》
《AI 3.0》