Request/Response【學習筆記03】

Request

Request 部分源碼:

# 部分代碼
class Request(object_ref):def __init__(self, url, callback=None, method='GET', headers=None, body=None, cookies=None, meta=None, encoding='utf-8', priority=0,dont_filter=False, errback=None):self._encoding = encoding  # this one has to be set firstself.method = str(method).upper()self._set_url(url)self._set_body(body)assert isinstance(priority, int), "Request priority not an integer: %r" % priorityself.priority = priorityassert callback or not errback, "Cannot use errback without a callback"self.callback = callbackself.errback = errbackself.cookies = cookies or {}self.headers = Headers(headers or {}, encoding=encoding)self.dont_filter = dont_filterself._meta = dict(meta) if meta else None@propertydef meta(self):if self._meta is None:self._meta = {}return self._meta

其中,比較常用的參數:

url: 就是需要請求,并進行下一步處理的urlcallback: 指定該請求返回的Response,由那個函數來處理。method: 請求一般不需要指定,默認GET方法,可設置為"GET", "POST", "PUT"等,且保證字符串大寫headers: 請求時,包含的頭文件。一般不需要。內容一般如下:# 自己寫過爬蟲的肯定知道Host: media.readthedocs.orgUser-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0Accept: text/css,*/*;q=0.1Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3Accept-Encoding: gzip, deflateReferer: http://scrapy-chs.readthedocs.org/zh_CN/0.24/Cookie: _ga=GA1.2.1612165614.1415584110;Connection: keep-aliveIf-Modified-Since: Mon, 25 Aug 2014 21:59:35 GMTCache-Control: max-age=0meta: 比較常用,在不同的請求之間傳遞數據使用的。字典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: 表明該請求不由調度器過濾。這是當你想使用多次執行相同的請求,忽略重復的過濾器。默認為False。errback: 指定錯誤處理函數

Response

# 部分代碼
class Response(object_ref):def __init__(self, url, status=200, headers=None, body='', flags=None, request=None):self.headers = Headers(headers or {})self.status = int(status)self._set_body(body)self._set_url(url)self.request = requestself.flags = [] if flags is None else list(flags)@propertydef meta(self):try:return self.request.metaexcept AttributeError:raise AttributeError("Response.meta not available, this response " \"is not tied to any request")

大部分參數和上面的差不多:


status: 響應碼
_set_body(body): 響應體
_set_url(url):響應url
self.request = request

發送POST請求

  • 可以使用?yield scrapy.FormRequest(url, formdata, callback)方法發送POST請求。

  • 如果希望程序執行一開始就發送POST請求,可以重寫Spider類的start_requests(self)方法,并且不再調用start_urls里的url。

class mySpider(scrapy.Spider):# start_urls = ["http://www.example.com/"]def start_requests(self):url = 'http://www.renren.com/PLogin.do'# FormRequest 是Scrapy發送POST請求的方法yield scrapy.FormRequest(url = url,formdata = {"email" : "mr_mao_hacker@163.com", "password" : "axxxxxxxe"},callback = self.parse_page)def parse_page(self, response):# do something

模擬登陸

使用FormRequest.from_response()方法模擬用戶登錄

通常網站通過?實現對某些表單字段(如數據或是登錄界面中的認證令牌等)的預填充。

使用Scrapy抓取網頁時,如果想要預填充或重寫像用戶名、用戶密碼這些表單字段, 可以使用 FormRequest.from_response() 方法實現。

下面是使用這種方法的爬蟲例子:

import scrapyclass LoginSpider(scrapy.Spider):name = 'example.com'start_urls = ['http://www.example.com/users/login.php']def parse(self, response):return scrapy.FormRequest.from_response(response,formdata={'username': 'john', 'password': 'secret'},callback=self.after_login)def after_login(self, response):# check login succeed before going onif "authentication failed" in response.body:self.log("Login failed", level=log.ERROR)return# continue scraping with authenticated session...

知乎爬蟲案例參考:

zhihuSpider.py爬蟲代碼

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from scrapy.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from scrapy.linkextractors import LinkExtractor
from scrapy import Request, FormRequest
from zhihu.items import ZhihuItemclass ZhihuSipder(CrawlSpider) :name = "zhihu"allowed_domains = ["www.zhihu.com"]start_urls = ["http://www.zhihu.com"]rules = (Rule(LinkExtractor(allow = ('/question/\d+#.*?', )), callback = 'parse_page', follow = True),Rule(LinkExtractor(allow = ('/question/\d+', )), callback = 'parse_page', follow = True),)headers = {"Accept": "*/*","Accept-Language": "en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4","Connection": "keep-alive","Content-Type":" application/x-www-form-urlencoded; charset=UTF-8","User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2125.111 Safari/537.36","Referer": "http://www.zhihu.com/"}#重寫了爬蟲類的方法, 實現了自定義請求, 運行成功后會調用callback回調函數def start_requests(self):return [Request("https://www.zhihu.com/login", meta = {'cookiejar' : 1}, callback = self.post_login)]def post_login(self, response):print 'Preparing login'#下面這句話用于抓取請求網頁后返回網頁中的_xsrf字段的文字, 用于成功提交表單xsrf = response.xpath('//input[@name="_xsrf"]/@value').extract()[0]print xsrf#FormRequeset.from_response是Scrapy提供的一個函數, 用于post表單#登陸成功后, 會調用after_login回調函數return [FormRequest.from_response(response,   #"http://www.zhihu.com/login",meta = {'cookiejar' : response.meta['cookiejar']},headers = self.headers,  #注意此處的headersformdata = {'_xsrf': xsrf,'email': '123456@qq.com','password': '123456'},callback = self.after_login,dont_filter = True)]def after_login(self, response) :for url in self.start_urls :yield self.make_requests_from_url(url)def parse_page(self, response):problem = Selector(response)item = ZhihuItem()item['url'] = response.urlitem['name'] = problem.xpath('//span[@class="name"]/text()').extract()print item['name']item['title'] = problem.xpath('//h2[@class="zm-item-title zm-editable-content"]/text()').extract()item['description'] = problem.xpath('//div[@class="zm-editable-content"]/text()').extract()item['answer']= problem.xpath('//div[@class=" zm-editable-content clearfix"]/text()').extract()return item

Item類設置

from scrapy.item import Item, Fieldclass ZhihuItem(Item):# define the fields for your item here like:# name = scrapy.Field()url = Field()  #保存抓取問題的urltitle = Field()  #抓取問題的標題description = Field()  #抓取問題的描述answer = Field()  #抓取問題的答案name = Field()  #個人用戶的名稱

setting.py 設置抓取間隔

BOT_NAME = 'zhihu'SPIDER_MODULES = ['zhihu.spiders']
NEWSPIDER_MODULE = 'zhihu.spiders'
DOWNLOAD_DELAY = 0.25   #設置下載間隔為250ms

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/456768.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/456768.shtml
英文地址,請注明出處:http://en.pswp.cn/news/456768.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

TotoiseSVN的上手教程

本文轉自:http://www.cnblogs.com/xilentz/archive/2010/05/06/1728945.html TotoiseSVN的基本使用方法: 一、簽入源代碼到SVN服務器 假如我們使用Visual Studio在文件夾StartKit中創建了一個項目,我們要把這個項目的源代碼簽入到SVN Serv…

ALV可輸入狀態下輸入金額字段變小數的問題

http://blog.163.com/mxb_sapyeah/blog/static/10335262520167109022155/ 小數位數兩位 當我在給ALV上給該字段輸入整數 ‘1234 ‘ 時,該數據居然會默認變成‘12.34’ 可以在這里解決這個問題。就是定義字段目錄的時候,對于金額字段指定參考數據類型就…

Downloader Middlewares反反爬蟲【學習筆記04】

反反爬蟲相關機制 Some websites implement certain measures to prevent bots from crawling them, with varying degrees of sophistication. Getting around those measures can be difficult and tricky, and may sometimes require special infrastructure. Please consi…

【轉載】Android 關于arm64-v8a、armeabi-v7a、armeabi、x86下的so文件兼容問題

轉自:【歐陽鵬】http://blog.csdn.net/ouyang_peng Android 設備的CPU類型(通常稱為”ABIs”) armeabiv-v7a: 第7代及以上的 ARM 處理器。2011年15月以后的生產的大部分Android設備都使用它.arm64-v8a: 第8代、64位ARM處理器,很少設備,三星 G…

HDFS的簡介及基本操作(常用的命令參數介紹)

目錄前言:1、HDFS基本概念2、HDFS基本操作總結: 目錄 前言: 總算有空來接著寫大數據的學習筆記了,今天就把之前學過的HDFS的基礎知識詳細的介紹一下,如有哪點寫的不足希望大家多多指教。 1、HDFS基本概念 1.1、前…

Settings【學習筆記05】

Settings Scrapy設置(settings)提供了定制Scrapy組件的方法。可以控制包括核心(core),插件(extension),pipeline及spider組件。比如 設置Json Pipeliine、LOG_LEVEL等。 參考文檔:http://scrapy-chs.readthedocs.io/zh_CN/1.0/topics/setti…

java命令

javac.exe是編譯.java文件java.exe是執行編譯好的.class文件javadoc.exe是生成Java說明文檔jdb.exe是Java調試器javaprof.exe是剖析工具轉載于:https://www.cnblogs.com/Berryxiong/p/6143016.html

TensorFlow訓練單特征和多特征的線性回歸

線性回歸 線性回歸是很常見的一種回歸,線性回歸可以用來預測或者分類,主要解決線性問題。相關知識可看“相關閱讀”。 主要思想 在TensorFlow中進行線性回歸處理重點是將樣本和樣本特征矩陣化。 單特征線性回歸 單特征回歸模型為:ywxb 構建模…

大數據之HDFS應用開發(java API)

目錄1、搭建開發環境2、獲取api中的客戶端對象3、DistributedFileSystem實例對象所具備的方法4、HDFS客戶端操作數據代碼示例 目錄 1、搭建開發環境 window下開發的說明: A、在windows的某個目錄下解壓一個hadoop的安裝包 B、將安裝包下的lib和bin目錄用對應windows版本平…

shell腳本執行方式,更方便更快捷。

在進行linux測試時編寫腳本是必不可少的。最近經常使用Linux,感覺太頻繁地敲擊鍵盤有些累了,于是想到了Shell腳本。可以把太多的命令寫成一個腳本,這樣每次執行一遍 shell文件,就可以省去了敲擊鍵盤的時間。于是在網上搜了一些有…

行為科學統計第1章

行為科學統計 Statistics for the Behavioral Sciences 一周只學習一次不如每周學習比較多的幾次高效噢~[一開始,你并不知道這是一個會寫著畫風突變的讀書筆記?…] 第I部分 簡述與描述性統計 第1章 統計學入門 這本書我就是覺得這…

閉包---在函數內部再定義一個函數

什么是閉包 # 定義一個函數 def test(number):# 在函數內部再定義一個函數,并且這個函數用到了外邊函數的變量,那么將這個函數以及用到的一些變量稱之為閉包def test_in(number_in):print("in test_in 函數, number_in is %d" % number_in)re…

慕課網_《Java實現對稱加密》學習總結

時間:2017年4月11日星期二說明:本文部分內容均來自慕課網。慕課網:http://www.imooc.com教學示例源碼:https://github.com/zccodere/s...個人學習源碼:https://github.com/zccodere/s... 第一章:對稱加密算…

大數據之MapReduce詳解(MR的運行機制及配合WordCount實例來說明運行機制)

目錄前言:1、MapReduce原理2、mapreduce實踐(WordCount實例) 目錄 今天先總體說下MapReduce的相關知識,后續將會詳細說明對應的shuffle、mr與yarn的聯系、以及mr的join操作的等知識。以下內容全是個人學習后的見解,如…

生動形象的理解什么是裝飾器!

裝飾器 裝飾器是程序開發中經常會用到的一個功能,用好了裝飾器,開發效率如虎添翼,所以這也是Python面試中必問的問題,但對于好多初次接觸這個知識的人來講,這個功能有點繞,自學時直接繞過去了,…

PLSQL 申明和游標

--從鍵盤輸入一個數 accept b prompt 請輸入一個大于零的數字; declareanum number : &b; beginwhile anum>0loopdbms_output.put_line(anum);anum:anum-1;end loop; end;declarev_num number; begin -- 從stsu表中選出id最大的值,并根據該值打印次數select …

20155222 2016-2017-2 《Java程序設計》第8周學習總結

20155222 2016-2017-2 《Java程序設計》第8周學習總結 教材學習內容總結 Java NIO(New IO)是一個可以替代標準Java IO API的IO API(從Java 1.4開始),Java NIO提供了與標準IO不同的IO工作方式。 Java NIO: Channels and Buffers(通道和緩沖區&…

BAT經典面試題精簡版(基礎知識附答案)

文章目錄目錄J2SE基礎JVM操作系統TCP/IP數據結構與算法目錄 J2SE基礎 九種基本數據類型的大小,以及他們的封裝類。 原始類型封裝類 booleanBoolean charCharacter byteByte shortShort intInteger longLong floatFloat doubleDouble Switch能否用string做參數&…

使用2to3.py 轉換 python2.x 代碼 到python3

1.使用Windows 命令提示符(cmd)cd到2to3.py 腳本所在位置,如下圖: 找不到的2 to 3.py的去 pycharm中雙擊shift搜索一下 2.緊接著運行 2to3.py 腳本(可省略) 3.執行你想要轉換的文件 python 2to3.py -w H:…

iis6.0與asp.net的運行原理

這幾天上網翻閱了不少前輩們的關于iis和asp.net運行原理的博客,學的有點零零散散,花了好長時間做了一個小結(雖然文字不多,但也花了不少時間呢),鄙人不才,難免有理解不道的地方,還望…