网络编程
位置:首页>> 网络编程>> Python编程>> 关于爬虫中scrapy.Request的更多参数用法

关于爬虫中scrapy.Request的更多参数用法

作者:黑马蓝汐  发布时间:2023-10-14 02:20:26 

标签:爬虫,scrapy,Request,参数

爬虫中scrapy.Request的更多参数

scrapy.Request的参数

scrapy.Request(url[,callback,method="GET",headers,body,cookies,meta,dont_filter=Fallse])

参数解释:

中括号中的参数为可选参数,可写可不写

  • callback:表示当前的url响应交给哪个函数去处理(默认为parse函数)

  • meta:实现数据在不同解析函数中传递,meta默认带有部分数据,比如下载延迟、请求深度等(用于解析方法之间的数据传递,常用在一条数据分散在多个不同结构的页面中的情况)

  • dont_filter:默认为False,会过滤请求的url地址,即请求过的url地址不会继续被请求,对需要重复请求的url地址可以把它设置为True,start_urls中的地址会被反复请求,否则程序不会启动

  • headers:接收一个字典,其中不包括cookies

  • cookies:接收一个字典,专门放置cookies

  • method:指定POST或GET请求

  • body:接收json字符串,为post的数据发送payload_post请求

meta参数

meta的作用:meta可以实现数据在不同的解析函数中的传递

在爬虫文件的parse方法中,增加一个函数parse_detail函数(用来解析另一个页面):

def parse(self,response):
    ...
    yield scrapy.Request(detail_url, callback=self.parse_detail,meta={"item":item})
...

def parse_detail(self,response):
    #获取之前传入的item
    item = resposne.meta["item"]

就相当于,把parse中解析的数据存到了meta字典中,对应的key为item;而在另一个函数(parse_detail)中,通过meta字典中的key:item来提取parse中的数据,从而实现不同页面数据的拼接

注意:

  • meta参数是一个字典

  • meta字典中有一个固定的键proxy,表示代理ip

scrapy中Request中常用参数

  • url: 就是需要请求,并进行下一步处理的url

  • callback: 指定该请求返回的Response,由那个函数来处理。

  • method: 一般不需要指定,使用默认GET方法请求即可

  • headers: 请求时,包含的头文件。一般不需要。内容一般如下:使用 urllib2 自己写过爬虫的肯定知道

Host: media.readthedocs.org
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0
Accept: text/css,*/*;q=0.1
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://scrapy-chs.readthedocs.org/zh_CN/0.24/
Cookie: _ga=GA1.2.1612165614.1415584110;
Connection: keep-alive
If-Modified-Since: Mon, 25 Aug 2014 21:59:35 GMT
Cache-Control: max-age=0
  • meta: 比较常用,在不同的请求之间传递数据使用的。字典dict型

request_with_cookies = Request(url="http://www.example.com",
       cookies={'currency': 'USD', 'country': 'UY'},
       meta={'dont_merge_cookies': True})
  • encoding: 使用默认的 'utf-8' 就行。

dont_filter: indicates that this request should not be filtered by the scheduler. 
     This is used when you want to perform an identical request multiple times, 
     to ignore the duplicates filter. Use it with care, or you will get into crawling loops. 
     Default to False.

  • errback: 指定错误处理函数

来源:https://blog.csdn.net/qq_52262831/article/details/121867006

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com