天天看點

22、Python快速開發分布式搜尋引擎Scrapy精講—scrapy模拟登陸和知乎倒立文字驗證碼識别

轉自:

http://www.bdyss.cn

http://www.swpan.cn

第一步。首先下載下傳,大神者也的倒立文字驗證碼識别程式

下載下傳位址:

https://github.com/muchrooms/zheye

注意:此程式依賴以下子產品包

  Keras==2.0.1

  Pillow==3.4.2

  jupyter==1.0.0

  matplotlib==1.5.3

  numpy==1.12.1

  scikit-learn==0.18.1

  tensorflow==1.0.1

  h5py==2.6.0

numpy-1.13.1+mkl

我們用豆瓣園來加速安以上依賴裝如:

pip install -i https://pypi.douban.com/simple h5py==2.6.0           

如果是win系統,可能存在安裝失敗的可能,如果那個包安裝失敗,就到

http://www.lfd.uci.edu/~gohlke/pythonlibs/

 找到win對應的版本下載下傳到本地安裝,如:

pip install h5py-2.7.0-cp35-cp35m-win_amd64.whl           

第二步,将者也的,驗證碼識别程式的zheye檔案夾放到工程目錄裡

22、Python快速開發分布式搜尋引擎Scrapy精講—scrapy模拟登陸和知乎倒立文字驗證碼識别

第三步,爬蟲實作

start_requests()方法,起始url函數,會替換start_urls

Request()方法,get方式請求網頁

  url=字元串類型url

  headers=字典類型浏覽器代理

  meta=字典類型的資料,會傳遞給回調函數

  callback=回調函數名稱

scrapy.FormRequest()post方式送出資料

  formdata=字典類型,要送出的資料字段

response.headers.getlist('Set-Cookie') 擷取響應Cookies

response.request.headers.getlist('Cookie') 擷取請求Cookies

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request,FormRequest
import re

class PachSpider(scrapy.Spider):                            #定義爬蟲類,必須繼承scrapy.Spider
    name = 'pach'                                           #設定爬蟲名稱
    allowed_domains = ['zhihu.com']                    #爬取域名
    # start_urls = ['']                                     #爬取網址,隻适于不需要登入的請求,因為沒法設定cookie等資訊

    header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0'}  #設定浏覽器使用者代理

    def start_requests(self):    #起始url函數,會替換start_urls
        """第一次請求一下登入頁面,設定開啟cookie使其得到cookie,設定回調函數"""
        return [Request(
            url='https://www.zhihu.com/#signin',
            headers=self.header,
            meta={'cookiejar':1},       #開啟Cookies記錄,将Cookies傳給回調函數
            callback=self.parse
        )]

    def parse(self, response):
        # 響應Cookies
        Cookie1 = response.headers.getlist('Set-Cookie')                            #檢視一下響應Cookie,也就是第一次通路注冊頁面時背景寫入浏覽器的Cookie
        print('背景首次寫入的響應Cookies:',Cookie1)

        #擷取xsrf密串
        xsrf = response.xpath('//input[@name="_xsrf"]/@value').extract()[0]
        print('擷取xsrf密串:' + xsrf)

        #擷取驗證碼         
        import time         
        t = str(int(time.time()*1000))         
        captcha_url = 'https://www.zhihu.com/captcha.gif?r={0}&type=login&lang=cn'.format(t)   #構造驗證碼請求位址
        yield Request(url=captcha_url,                                                         #請求驗證碼圖檔
                      headers=self.header,
                      meta={'cookiejar':response.meta['cookiejar'],'xsrf':xsrf},               #将Cookies和xsrf密串傳給回調函數
                      callback=self.post_tj
                      )

    def post_tj(self, response):
        with open('yzhm.jpg','wb') as f:        #打開圖檔句柄
            f.write(response.body)              #将驗證碼圖檔寫入本地
            f.close()                           #關閉句柄

#---------------------------者也驗證碼識别-----------------------

        from zheye import zheye                 #導入者也倒立文字驗證碼識别子產品對象
        z = zheye()                             #執行個體化對象
        positions = z.Recognize('yzhm.jpg')     #将驗證碼本地路徑傳入Recognize方法識别,傳回倒立圖檔的坐标
        # print(positions)                      #預設倒立文字的y坐标在前,x坐标在後

        #知乎網要求的倒立文字坐标是x軸在前,y軸在後,是以我們需要定義一個清單來改變預設的,倒立文字坐标位置
        pos_arr = []
        if len(positions) == 2:
            if positions[0][1] > positions[1][1]:                      #判斷清單裡第一個元祖裡的第二個元素如果大于,第二個元祖裡的第二個元素
                pos_arr.append([positions[1][1],positions[1][0]])
                pos_arr.append([positions[0][1], positions[0][0]])
            else:
                pos_arr.append([positions[0][1], positions[0][0]])
                pos_arr.append([positions[1][1], positions[1][0]])
        else:
            pos_arr.append([positions[0][1], positions[0][0]])

        print('處理後的驗證碼坐标',pos_arr)

# -------------者也驗證碼識别結束--------

        if len(pos_arr) == 2:
            data = {                                                                    # 設定使用者登入資訊,對應抓包得到字段
                '_xsrf': response.meta['xsrf'],
                'password': '279819',
                'captcha': '{"img_size":[200,44],"input_points":[[%.2f,%f],[%.2f,%f]]}' %(
                    pos_arr[0][0] / 2, pos_arr[0][1] / 2, pos_arr[1][0] / 2, pos_arr[1][1] / 2),  #因為驗證碼識别預設是400X88的尺寸是以要除以2
                'captcha_type': 'cn',
                'phone_num': '15284816568'
            }
        else:
            data = {                                                                    # 設定使用者登入資訊,對應抓包得到字段
                '_xsrf': response.meta['xsrf'],
                'password': '279819',
                'captcha': '{"img_size":[200,44],"input_points":[[%.2f,%f]]}' %(
                    pos_arr[0][0] / 2, pos_arr[0][1] / 2),
                'captcha_type': 'cn',
                'phone_num': '15284816568'
            }

        print('登入送出資料',data)

        print('登入中....!')
        """第二次用表單post請求,攜帶Cookie、浏覽器代理、使用者登入資訊,進行登入給Cookie授權"""
        return [scrapy.FormRequest(
            url='https://www.zhihu.com/login/phone_num',                        #真實post位址
            meta={'cookiejar':response.meta['cookiejar']},                      #接收第傳過來的Cookies
            headers=self.header,
            formdata=data,
            callback=self.next
        )]

    def next(self,response):
        # 請求Cookie
        Cookie2 = response.request.headers.getlist('Cookie')
        print('登入時攜帶請求的Cookies:',Cookie2)

        jieg = response.body.decode("utf-8")   #登入後可以檢視一下登入響應資訊
        print('登入響應結果:',jieg)

        print('正在請需要登入才可以通路的頁面....!')

        """登入後請求需要登入才能檢視的頁面,如個人中心,攜帶授權後的Cookie請求"""
        yield Request(
            url='https://www.zhihu.com/people/lin-gui-xiu-41/activities',
            headers=self.header,
            meta={'cookiejar':True},
            callback=self.next2
        )

    def next2(self,response):
        # 請求Cookie
        Cookie3 = response.request.headers.getlist('Cookie')
        print('檢視需要登入才可以通路的頁面攜帶Cookies:',Cookie3)

        leir = response.xpath('/html/head/title/text()').extract()  #得到個人中心頁面
        print('最終内容',leir)
        # print(response.body.decode("utf-8"))           
22、Python快速開發分布式搜尋引擎Scrapy精講—scrapy模拟登陸和知乎倒立文字驗證碼識别

【轉載自:

http://www.lqkweb.com