偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

網絡爬蟲框架Scrapy詳解之Request

開發(fā) 后端
Request類是一個http請求的類,對于爬蟲而言是一個很重要的類。通常在Spider中創(chuàng)建這樣的一個請求,在Downloader中執(zhí)行這樣的一個請求。同時也有一個子類FormRequest繼承于它,用于post請求。

[[239300]]

介紹

Request類是一個http請求的類,對于爬蟲而言是一個很重要的類。通常在Spider中創(chuàng)建這樣的一個請求,在Downloader中執(zhí)行這樣的一個請求。同時也有一個子類FormRequest繼承于它,用于post請求。

在Spider中通常用法:   

  1. yield scrapy.Request(url = 'zarten.com'

類屬性和方法有: 

  • url  
  • method  
  • headers  
  • body  
  • meta  
  • copy()  
  • replace([url, method, headers, body, cookies, meta, encoding, dont_filter, callback, errback]) 

Request   

  1. class scrapy.http.Request(url[, callback, method='GET', headers, body, cookies, meta, encoding='utf-8'priority=0dont_filter=False, errback, flags]) 

參數說明:

  •  url 請求的url
  •  callback 回調函數,用于接收請求后的返回信息,若沒指定,則默認為parse()函數
  •  method http請求的方式,默認為GET請求,一般不需要指定。若需要POST請求,用FormRequest即可
  •  headers 請求頭信息,一般在settings中設置即可,也可在middlewares中設置
  •  body str類型,為請求體,一般不需要設置(get和post其實都可以通過body來傳遞參數,不過一般不用)
  •  cookies dict或list類型,請求的cookie dict方式(name和value的鍵值對):   
  1. cookies = {'name1' : 'value1' , 'name2' : 'value2'} 

list方式:   

  1. cookies = [  
  2.    {'name': 'Zarten', 'value': 'my name is Zarten', 'domain': 'example.com', 'path': '/currency'}  
  3.    ] 
  •  encoding 請求的編碼方式,默認為'utf-8'
  •  priority int類型,指定請求的優(yōu)先級,數字越大優(yōu)先級越高,可以為負數,默認為0
  •  dont_filter 默認為False,若設置為True,這次請求將不會過濾(不會加入到去重隊列中),可以多次執(zhí)行相同的請求
  •  errback 拋出錯誤的回調函數,錯誤包括404,超時,DNS錯誤等,***個參數為Twisted Failure實例   
  1. from scrapy.spidermiddlewares.httperror import HttpError  
  2.    from twisted.internet.error import DNSLookupError  
  3.    from twisted.internet.error import TimeoutError, TCPTimedOutError  
  4.    class ToScrapeCSSSpider(scrapy.Spider):  
  5.        name = "toscrape-css"  
  6.        # start_urls = [  
  7.        #     'http://quotes.toscrape.com/',  
  8.        # ]  
  9.        start_urls = [  
  10.            "http://www.httpbin.org/",  # HTTP 200 expected  
  11.            "http://www.httpbin.org/status/404",  # Not found error  
  12.            "http://www.httpbin.org/status/500",  # server issue  
  13.            "http://www.httpbin.org:12345/",  # non-responding host, timeout expected  
  14.            "http://www.httphttpbinbin.org/",  # DNS error expected  
  15.        ]  
  16.        def start_requests(self):  
  17.            for u in self.start_urls:  
  18.                yield scrapy.Request(u, callback=self.parse_httpbin,  
  19.                                     errback=self.errback_httpbin,  
  20.                                     dont_filter=True 
  21.        def parse_httpbin(self, response):  
  22.            self.logger.info('Got successful response from {}'.format(response.url))  
  23.            # do something useful here...  
  24.        def errback_httpbin(self, failure):  
  25.            # log all failures  
  26.            self.logger.info(repr(failure))  
  27.            # in case you want to do something special for some errors,  
  28.            # you may need the failure's type:  
  29.            if failure.check(HttpError):  
  30.                # these exceptions come from HttpError spider middleware  
  31.                # you can get the non-200 response  
  32.                response = failure.value.response  
  33.                self.logger.info('HttpError錯誤 on %s', response.url)  
  34.            elif failure.check(DNSLookupError):  
  35.                # this is the original request  
  36.                request = failure.request  
  37.                self.logger.info('DNSLookupError錯誤 on %s', request.url)  
  38.            elif failure.check(TimeoutError, TCPTimedOutError):  
  39.                request = failure.request  
  40.                self.logger.info('TimeoutError錯誤 on %s', request.url) 
  •  flags list類型,一般不會用到,發(fā)送請求的標志,一般用于日志記錄
  •  meta 可用戶自定義從Request到Response傳遞參數,這個參數一般也可在middlewares中處理   
  1. yield scrapy.Request(url = 'zarten.com'meta = {'name' : 'Zarten'}) 

在Response中: 

  1. my_name = response.meta['name'] 

不過也有scrapy內置的特殊key,也非常有用,它們如下:

  •  proxy 設置代理,一般在middlewares中設置

可以設置http或https代理 

  1. request.meta['proxy'] = 'https://' + 'ip:port' 
  •  downloadtimeout 設置請求超時等待時間(秒),通常在settings中設置DOWNLOADTIMEOUT,默認是180秒(3分鐘)
  •  maxretrytimes ***重試次數(除去***次下載),默認為2次,通常在settings中 RETRY_TIMES設置
  •  dont_redirect 設為True后,Request將不會重定向
  •  dont_retry 設為True后,對于http鏈接錯誤或超時的請求將不再重試請求
  •  handlehttpstatuslist http返回碼200-300之間都是成功的返回,超出這個范圍的都是失敗返回,scrapy默認是過濾了這些返回,不會接收這些錯誤的返回進行處理。不過可以自定義處理哪些錯誤返回:   
  1. yield scrapy.Request(url'https://httpbin.org/get/zarten'meta= {'handle_httpstatus_list' : [404]}) 

在parse函數中可以看到處理404錯誤:     

  1. def parse(self, response):  
  2.     print('返回信息為:',response.text) 
  •  handlehttpstatusall 設為True后,Response將接收處理任意狀態(tài)碼的返回信息
  •  dontmergecookies scrapy會自動保存返回的cookies,用于它的下次請求,當我們指定了自定義cookies時,如果我們不需要合并返回的cookies而使用自己指定的cookies,可以設為True
  •  cookiejar 可以在單個spider中追蹤多個cookie,它不是粘性的,需要在每次請求時都帶上       
  1. def start_requests(self):  
  2.            urls = ['http://quotes.toscrape.com/page/1',  
  3.                    'http://quotes.toscrape.com/page/3',  
  4.                    'http://quotes.toscrape.com/page/5',  
  5.                    ]  
  6.            for i ,url in enumerate(urls):  
  7.                yield scrapy.Request(urlurl= url, meta= {'cookiejar' : i})  
  8.        def parse(self, response):  
  9.            next_page_url = response.css("li.next > a::attr(href)").extract_first()  
  10.            if next_page_url is not None:  
  11.                yield scrapy.Request(response.urljoin(next_page_url), meta= {'cookiejar' : response.meta['cookiejar']}, callbackself.parse_next)  
  12.        def parse_next(self, response):  
  13.            print('cookiejar:', response.meta['cookiejar']) 
  •  dont_cache 設為True后,不會緩存
  •  redirect_urls 暫時還不清楚具體的作用,知道的小伙伴們歡迎在評論留言
  •  bindaddress 綁定輸出IP
  •  dontobeyrobotstxt 設為True,不遵守robots協議,通常在settings中設置
  •  downloadmaxsize 設置下載器***下載的大?。ㄗ止?jié)),通常在settings中設置DOWNLOADMAXSIZE,默認為1073741824 (1024MB=1G),若不設置***的下載限制,設為0
  •  download_latency 只讀屬性,獲取請求的響應時間(秒)       
  1. def start_requests(self):  
  2.            headers = {  
  3.                'user-agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'  
  4.            }  
  5.            yield scrapy.Request(url'https://www.amazon.com'headersheaders= headers)  
  6.        def parse(self, response):  
  7.            print('響應時間為:', response.meta['download_latency']) 
  •  downloadfailon_dataloss 很少用到,詳情看這里
  •  referrer_policy 設置Referrer Policy

FormRequest

FormRequest 類為Request的子類,用于POST請求

這個類新增了一個參數 formdata,其他參數與Request一樣,詳細可參考上面的講述

一般用法為:   

  1. yield scrapy.FormRequest(url="http://www.example.com/post/action" 
  2.                        formdata={'name': 'Zarten', 'age': '27'},  
  3.                        callback=self.after_post)  
責任編輯:龐桂玉 來源: Python中文社區(qū)
相關推薦

2021-01-08 09:07:19

Scrapy框架爬蟲

2017-05-15 21:00:15

大數據Scrapy爬蟲框架

2017-11-29 15:21:53

PythonScrapy爬蟲

2020-12-07 11:23:32

Scrapy爬蟲Python

2017-09-16 17:45:32

數據采集Scrapy爬蟲

2021-11-09 09:46:09

ScrapyPython爬蟲

2021-11-08 14:38:50

框架Scrapy 爬蟲

2021-04-12 07:36:15

Scrapy爬蟲框架

2021-05-18 13:25:28

feapder爬蟲Python

2020-11-11 10:58:59

Scrapy

2018-05-16 13:50:30

Python網絡爬蟲Scrapy

2021-01-30 10:37:18

ScrapyGerapy網絡爬蟲

2020-10-27 08:33:38

Scrapy

2018-05-14 16:34:08

Python網絡爬蟲Scrapy

2017-02-23 18:41:03

數據分析師Python網絡爬蟲

2011-08-08 17:59:22

UIWebView網絡網頁

2017-11-20 09:46:08

python爬蟲Scrapy

2012-07-17 09:13:14

Scrapy

2023-01-12 08:00:00

SpringClou微服務框架

2023-02-07 07:43:27

微服務應用框架
點贊
收藏

51CTO技術棧公眾號