Scrapy中通过scrapy.Request发送网络请求,核心参数包括url、callback、method、headers、body、meta、cookies和dont_filter;可使用FormRequest提交表单,response.follow()快捷跟进链接,实现灵活的爬虫控制流程。

Scrapy 中的 scrapy.Request 是发送网络请求的核心方式。通过它,你可以发起 HTTP/HTTPS 请求并指定回调函数处理响应。以下是使用 scrapy.Request 发送请求的常见方式和关键参数说明。
基本用法:创建一个简单的 Request
最基础的用法是实例化一个 Request 对象,并传入 URL 和回调函数:
import scrapyclass MySpider(scrapy.Spider): name = 'example'
def start_requests(self): yield scrapy.Request( url='https://httpbin.org/get', callback=self.parse ) def parse(self, response): self.log(f"Status: {response.status}") self.log(f"Body: {response.text[:200]}")
常用参数详解
scrapy.Request 支持多个参数来控制请求行为:
- url:请求的目标地址(必须)
-
callback:响应返回后调用的解析函数,默认为
parse - method:HTTP 方法,如 "GET", "POST"
- headers:自定义请求头字典
- body:请求体内容,用于 POST 等方法
- meta:在请求和响应之间传递数据的字典
- cookies:设置 Cookie 字典或列表
- dont_filter:是否跳过去重过滤,默认为 False
立即学习“Python免费学习笔记(深入)”;
yield scrapy.Request(
url='https://httpbin.org/post',
method='POST',
headers={'Content-Type': 'application/json'},
body='{"key": "value"}',
cookies={'session_id': '12345'},
meta={'page_type': 'login'},
callback=self.after_post
)
使用 FormRequest 提交表单
如果需要模拟表单提交,推荐使用 scrapy.FormRequest,它是 Request 的子类,专门用于发送表单数据:
yield scrapy.FormRequest(
url='https://httpbin.org/post',
formdata={'username': 'test', 'password': '123'},
callback=self.after_login
)
Scrapy 会自动设置 Content-Type 并编码表单数据(application/x-www-form-urlencoded)。
在 parse 中继续发送请求
在解析页面时,常需要根据当前响应发起新请求,比如翻页或进入详情页:
def parse(self, response):
# 解析链接并跟进
for href in response.css('a::attr(href)').getall():
yield response.follow(href, callback=self.parse_detail)
# 或者手动构造 Request
next_page = response.css('.next::attr(href)').get()
if next_page:
yield scrapy.Request(next_page, callback=self.parse)注意:response.follow() 是快捷方式,内部也是生成 scrapy.Request,适合相对链接处理。
基本上就这些。掌握 scrapy.Request 的参数和使用场景,就能灵活控制爬虫的请求流程。











