Scrapy實現(xiàn)模擬登錄的示例代碼
為什么要模擬登錄
有些網(wǎng)站是需要登錄之后才能訪問的,即便是同一個網(wǎng)站,在用戶登錄前后頁面所展示的內(nèi)容也可能會大不相同,例如,未登錄時訪問Github首頁將會是以下的注冊頁面:

然而,登錄后訪問Github首頁將包含如下頁面內(nèi)容:

如果我們要爬取的是一些需要登錄之后才能訪問的頁面數(shù)據(jù)就需要模擬登錄了。通常我們都是利用的 Cookies 來實現(xiàn)模擬登錄,在Scrapy中,模擬登陸網(wǎng)站一般有如下兩種實現(xiàn)方式:
(1) 請求時攜帶Cookies
(2) 發(fā)送Post請求獲取Cookies
請求時攜帶Cookies
對于一些Cookies過期時間很長的不規(guī)范網(wǎng)站,如果我們能夠在Cookies過期之前爬取到所有我們想要的數(shù)據(jù),可以考慮在請求時直接將Cookies信息帶上來模擬用戶登錄。
以下是模擬登錄Github的示例代碼:
# -*- coding: utf-8 -*-
import scrapy
import re
class TmallLoginSpider(scrapy.Spider):
name = 'github_login3'
allowed_domains = ['github.com']
start_urls = ['https://github.com/']
def start_requests(self): # 請求時攜帶Cookies
cookies = '_ga=GA1.2.363045452.1554860671; tz=Asia%2FShanghai; _octo=GH1.1.1405577398.1554860677; _device_id=ee3ff12512668a1f9dc6fb33e388ea20; ignored_unsupported_browser_notice=false; has_recent_activity=1; user_session=5oxrsfsZCor1iJFCgRXXyeAXd8hcmzEUGh70-xHWLjQkT62Q; __Host-user_session_same_site=5oxrsfsZCor1iJFCgRXXyeAXd8hcmzEUGh70-xHWLjQkT62Q; logged_in=yes; dotcom_user=pengjunlee; _gat=1'
cookies = {i.split('=')[0]: i.split('=')[1] for i in cookies.split('; ')}
yield scrapy.Request(self.start_urls[0], cookies=cookies)
def parse(self, response): # 驗證是否請求成功
print(re.findall('Learn Git and GitHub without any code!',response.body.decode()))
執(zhí)行爬蟲后,后臺部分日志截圖如下:
![]()
發(fā)送Post請求模擬登錄
Scrapy還提供了兩種通過發(fā)送Post請求來獲取Cookies的方法。
scrapy.FormRequest()
使用scrapy.FormRequest()發(fā)送Post請求實現(xiàn)模擬登陸,需要人為找出登錄請求的地址以及構(gòu)造出登錄時所需的請求數(shù)據(jù)。
使用scrapy.FormRequest()模擬登錄Github的示例代碼:
# -*- coding: utf-8 -*-
import scrapy
import re
class GithubLoginSpider(scrapy.Spider):
name = 'github_login'
allowed_domains = ['github.com']
start_urls = ['https://github.com/login']
def parse(self, response): # 發(fā)送Post請求獲取Cookies
authenticity_token = response.xpath('//input[@name="authenticity_token"]/@value').extract_first()
utf8 = response.xpath('//input[@name="utf8"]/@value').extract_first()
commit = response.xpath('//input[@name="commit"]/@value').extract_first()
form_data = {
'login': 'pengjunlee@163.com',
'password': '123456',
'webauthn-support': 'supported',
'authenticity_token': authenticity_token,
'utf8': utf8,
'commit': commit}
yield scrapy.FormRequest("https://github.com/session", formdata=form_data, callback=self.after_login)
def after_login(self, response): # 驗證是否請求成功
print(re.findall('Learn Git and GitHub without any code!', response.body.decode()))
從后臺日志不難看出,Scrapy 在請求完 https://github.com/session 后,自動幫我們重定向到了Github首頁。
![]()
scrapy.FormRequest.from_response()
scrapy.FormRequest.from_response()使用起來比 scrapy.FormRequest()更加簡單方便,我們通常只需要提供用戶相關(guān)信息(賬戶和密碼)即可,scrapy.FormRequest.from_response()將通過模擬點擊為我們填充好其他的表單字段并提交表單。
使用scrapy.FormRequest.from_response()模擬登錄Github的示例代碼:
# -*- coding: utf-8 -*-
import scrapy
import re
class GithubLogin2Spider(scrapy.Spider):
name = 'github_login2'
allowed_domains = ['github.com']
start_urls = ['https://github.com/login']
def parse(self, response): # 發(fā)送Post請求獲取Cookies
form_data = {
'login': 'pengjunlee@163.com',
'password': '123456'
}
yield scrapy.FormRequest.from_response(response,formdata=form_data,callback=self.after_login)
def after_login(self,response): # 驗證是否請求成功
print(re.findall('Learn Git and GitHub without any code!',response.body.decode()))
scrapy.FormRequest.from_response()方法還可以傳入其他參數(shù)來幫我們更加精確的指定表單元素:
''' response (Response object) – 包含表單HTML的響應(yīng),將用來對表單的字段進(jìn)行預(yù)填充 formname (string) – 如果設(shè)置了該值,name 等于該值的表單將被使用 formid (string) – 如果設(shè)置了該值,id 等于該值的表單將被使用 formxpath (string) – 如果設(shè)置了該值,匹配該 xpath 的第一個表單將被使用 formcss (string) – 如果設(shè)置了該值,匹配該 css選擇器的第一個表單將被使用 formnumber (integer) – 索引值等于該值的表單將被使用,默認(rèn)第一個(索引值為 0 ) formdata (dict) – 傳入的表單數(shù)據(jù),將覆蓋form 元素中已經(jīng)存在的值 clickdata (dict) – 用于查找可點擊控件的屬性值 dont_click (boolean) – 如果設(shè)置為 True,將不點擊任何元素,直接提交表單數(shù)據(jù) '''
參考文章
https://doc.scrapy.org/en/latest/topics/request-response.html
到此這篇關(guān)于Scrapy實現(xiàn)模擬登錄的示例代碼的文章就介紹到這了,更多相關(guān)Scrapy 模擬登錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)火柴人的設(shè)計與實現(xiàn)
火柴人(Stick Figure)是一種極簡風(fēng)格的圖形,通常由簡單的線段和圓圈組成,卻能生動地表達(dá)人物的姿態(tài)和動作,本文旨在介紹如何使用Python實現(xiàn)火柴人的設(shè)計與繪制,通過編程的方式,讓讀者了解火柴人背后的基本原理和實現(xiàn)方法,需要的朋友可以參考下2024-10-10
Python統(tǒng)計分析模塊statistics用法示例
這篇文章主要介紹了Python統(tǒng)計分析模塊statistics用法,結(jié)合實例形式分析了Python統(tǒng)計分析模塊statistics計算平均數(shù)、中位數(shù)、出現(xiàn)次數(shù)、標(biāo)準(zhǔn)差等相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
python 中 .py文件 轉(zhuǎn) .pyd文件的操作
這篇文章主要介紹了python 中 .py文件 轉(zhuǎn) .pyd文件的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Python使用scrapy采集數(shù)據(jù)過程中放回下載過大頁面的方法
這篇文章主要介紹了Python使用scrapy采集數(shù)據(jù)過程中放回下載過大頁面的方法,可實現(xiàn)限制下載過大頁面的功能,非常具有實用價值,需要的朋友可以參考下2015-04-04
python類的方法屬性與方法屬性的動態(tài)綁定代碼詳解
這篇文章主要介紹了python類的方法屬性與方法屬性的動態(tài)綁定代碼詳解,具有一定借鑒價值,需要的朋友可以參考下2017-12-12

