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

Scrapy 中的 scrapy.Request 是发送网络请求的核心方式。通过它,你可以发起 HTTP/HTTPS 请求并指定回调函数处理响应。以下是使用 scrapy.Request 发送请求的常见方式和关键参数说明。
最基础的用法是实例化一个 Request 对象,并传入 URL 和回调函数:
import scrapy
<p>class MySpider(scrapy.Spider):
name = 'example'</p><pre class='brush:python;toolbar:false;'>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 支持多个参数来控制请求行为:
parse
立即学习“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
)
如果需要模拟表单提交,推荐使用 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)。
在解析页面时,常需要根据当前响应发起新请求,比如翻页或进入详情页:
def parse(self, response):
# 解析链接并跟进
for href in response.css('a::attr(href)').getall():
yield response.follow(href, callback=self.parse_detail)
<pre class='brush:python;toolbar:false;'># 或者手动构造 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 的参数和使用场景,就能灵活控制爬虫的请求流程。
以上就是python scrapy.Request发送请求的方式的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号