
第九章 爬虫类模块
本文主要叙述网路数据获取以及网页解析相关的模块,掌握此模块有利于在相关网页获取有价值的信息。主要包括以下几个模块:
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.txtfrom urllib import request
url = "https://httpbin.org/get"
with request.urlopen(url) as resp:
data = resp.read().decode('utf-8')
print(data)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())headers = {'User-Agent': 'Mozilla/5.0'}
req = request.Request(url, headers=headers)
resp = request.urlopen(req)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']}requests —— 最流行的 HTTP 库“人类友好的 HTTP 库”,简洁、强大、社区广泛,是绝大多数项目的首选。
pip install requestsimport 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())headers = {'User-Agent': 'MyBot/1.0'}
resp = requests.get(url, headers=headers, timeout=5)session = requests.Session()
session.headers.update({'User-Agent': 'MyApp'})
# 登录后自动携带 Cookie
session.post(login_url, data=login_data)
profile = session.get(profile_url) # 已登录状态# 上传文件
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)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'}verify=False(不推荐生产用)allow_redirects=False三、selenium —— 浏览器自动化神器控制真实浏览器(Chrome/Firefox),能执行 JavaScript、处理动态渲染页面(如 React/Vue 单页应用)。
pip install selenium
# 并下载对应浏览器驱动(如 chromedriver)
# 推荐使用 webdriver-manager 自动管理:
pip install webdriver-managerfrom 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()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")))# 点击
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);")html = driver.page_source # 包含 JS 执行后的完整 DOMfrom selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless") # 无界面
driver = webdriver.Chrome(options=options)BeautifulSoup —— HTML/XML 解析利器不是网络请求库! 专门用于解析 HTML/XML 文档,提取结构化数据。
pip install beautifulsoup4
# 推荐搭配解析器 lxml(更快更容错):
pip install lxmlfrom 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'# 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'] # /page2tag = soup.div
print(tag.get_text()) # Item 1
print(tag['class']) # ['item']
print(tag.attrs) # {'class': ['item']}# 从 requests 获取 HTML
resp = requests.get(url)
soup = BeautifulSoup(resp.text, 'lxml')
# 从 selenium 获取 HTML
soup = BeautifulSoup(driver.page_source, 'lxml')五、Scrapy —— 专业级爬虫框架全功能爬虫框架,支持并发、去重、中间件、管道、分布式等企业级特性。
pip install scrapyscrapy 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 # 爬虫逻辑# items.py
import scrapy
class QuoteItem(scrapy.Item):
text = scrapy.Field()
author = scrapy.Field()
tags = scrapy.Field()# 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)# 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 itemscrapy crawl quotes
# 输出到 JSON
scrapy crawl quotes -o quotes.jsonAUTOTHROTTLE_ENABLED = TrueCONCURRENT_REQUESTS = 16scrapy-selenium 插件)工具 | 类型 | 是否发请求 | 是否解析 HTML | 是否执行 JS | 适用场景 |
|---|---|---|---|---|---|
| 标准库 HTTP 客户端 | ✅ | ❌ | ❌ | 简单请求、教学 |
| 第三方 HTTP 库 | ✅ | ❌ | ❌ | API 调用、静态页抓取 |
| 浏览器自动化 | ✅(通过浏览器) | ❌(需配合解析器) | ✅ | 动态页、登录、JS 渲染 |
| HTML 解析器 | ❌ | ✅ | ❌ | 数据提取、清洗 |
| 爬虫框架 | ✅ | ✅(内置 Selector) | ❌(需插件) | 大规模、结构化爬虫 |
💡 典型组合:静态页面:
requests + BeautifulSoup动态页面:selenium + BeautifulSoup大型项目:Scrapy(可集成selenium处理动态内容)
requests(除非不能装第三方,才用 urllib)seleniumBeautifulSoup(或 Scrapy 的 response.css()/xpath())Scrapyrobots.txt(可用 urllib.robotparser 解析)🌐 合法合规,才是长久之道。
公众号:咚咚王
《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》
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。