python網絡爬蟲——requests高階部分:模擬登錄與驗證碼處理


雲打碼平台【處理各類驗證碼的平台】

  • 注冊:普通用戶和開發者用戶
  • 登錄:
    • 登錄普通用戶(查看余額)
    • 登錄開發者用戶:
      • 創建一個軟件:我的軟件->創建軟件
      • 下載示例代碼:開發者中心->下載最新的DLL->pythonHttp示例代碼下載
 
  • 一般點擊登錄按鈕的請求都是post請求
 
  • cookie的作用,服務器使用cookie記錄客戶端的狀態:經典:免密登錄
  • 服務端創建,客戶端存儲
  • 有有效時長,動態變化

引入

有些時候,我們在使用爬蟲程序去爬取一些用戶相關信息的數據(爬取張三“人人網”個人主頁數據)時,如果使用之前requests模塊常規操作時,往往達不到我們想要的目的,例如:

import requests
if __name__ == "__main__":

    #張三人人網個人信息頁面的url
    url = 'http://www.renren.com/289676607/profile'

   #偽裝UA
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    #發送請求,獲取響應對象
    response = requests.get(url=url,headers=headers)
    #將響應內容寫入文件
    with open('./renren.html','w',encoding='utf-8') as fp:
        fp.write(response.text)

 

基於requests模塊的cookie操作

  - 首先我們來回顧下cookie的相關概念及作用:

    - cookie概念:當用戶通過瀏覽器首次訪問一個域名時,訪問的web服務器會給客戶端發送數據,以保持web服務器與客戶端之間的狀態保持,這些數據就是cookie。

    - cookie作用:我們在瀏覽器中,經常涉及到數據的交換,比如你登錄郵箱,登錄一個頁面。我們經常會在此時設置30天內記住我,或者自動登錄選項。那么它們是怎么記錄信息的呢,答案就是今天的主角cookie了,Cookie是由HTTP服務器設置的,保存在瀏覽器中,但HTTP協議是一種無狀態協議,在數據交換完畢后,服務器端和客戶端的鏈接就會關閉,每次交換數據都需要建立新的鏈接。就像我們去超市買東西,沒有積分卡的情況下,我們買完東西之后,超市沒有我們的任何消費信息,但我們辦了積分卡之后,超市就有了我們的消費信息。cookie就像是積分卡,可以保存積分,商品就是我們的信息,超市的系統就像服務器后台,http協議就是交易的過程。

  - 經過cookie的相關介紹,其實你已經知道了為什么上述案例中爬取到的不是張三個人信息頁,而是登錄頁面。那應該如何抓取到張三的個人信息頁呢?

  思路:

    1.我們需要使用爬蟲程序對人人網的登錄時的請求進行一次抓取,獲取請求中的cookie數據

    2.在使用個人信息頁的url進行請求時,該請求需要攜帶 1 中的cookie,只有攜帶了cookie后,服務器才可識別這次請求的用戶信息,方可響應回指定的用戶信息頁數據

import requests
if __name__ == "__main__":

    #登錄請求的url(通過抓包工具獲取)
    post_url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=201873958471'
    #創建一個session對象,該對象會自動將請求中的cookie進行存儲和攜帶
    session = requests.session()
    #偽裝UA
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    formdata = {
        'email': '17701256561',
        'icode': '',
        'origURL': 'http://www.renren.com/home',
        'domain': 'renren.com',
        'key_id': '1',
        'captcha_type': 'web_login',
        'password': '7b456e6c3eb6615b2e122a2942ef3845da1f91e3de075179079a3b84952508e4',
        'rkey': '44fd96c219c593f3c9612360c80310a3',
        'f': 'https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3Dm7m_NSUp5Ri_ZrK5eNIpn_dMs48UAcvT-N_kmysWgYW%26wd%3D%26eqid%3Dba95daf5000065ce000000035b120219',
    }
    #使用session發送請求,目的是為了將session保存該次請求中的cookie
    session.post(url=post_url,data=formdata,headers=headers)

    get_url = 'http://www.renren.com/960481378/profile'
    #再次使用session進行請求的發送,該次請求中已經攜帶了cookie
    response = session.get(url=get_url,headers=headers)
    #設置響應內容的編碼格式
    response.encoding = 'utf-8'
    #將響應內容寫入文件
    with open('./renren.html','w') as fp:
        fp.write(response.text)

 

雲打碼處理驗證碼方法(直接引用即可)

import http.client, mimetypes, urllib, json, time, requests


class YDMHttp:

    apiurl = 'http://api.yundama.com/api.php'
    username = ''
    password = ''
    appid = ''
    appkey = ''

    def __init__(self, username, password, appid, appkey):
        self.username = username  
        self.password = password
        self.appid = str(appid)
        self.appkey = appkey

    def request(self, fields, files=[]):
        response = self.post_url(self.apiurl, fields, files)
        response = json.loads(response)
        return response
    
    def balance(self):
        data = {'method': 'balance', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
        response = self.request(data)
        if (response):
            if (response['ret'] and response['ret'] < 0):
                return response['ret']
            else:
                return response['balance']
        else:
            return -9001
    
    def login(self):
        data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
        response = self.request(data)
        if (response):
            if (response['ret'] and response['ret'] < 0):
                return response['ret']
            else:
                return response['uid']
        else:
            return -9001

    def upload(self, filename, codetype, timeout):
        data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
        file = {'file': filename}
        response = self.request(data, file)
        if (response):
            if (response['ret'] and response['ret'] < 0):
                return response['ret']
            else:
                return response['cid']
        else:
            return -9001

    def result(self, cid):
        data = {'method': 'result', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'cid': str(cid)}
        response = self.request(data)
        return response and response['text'] or ''

    def decode(self, filename, codetype, timeout):
        cid = self.upload(filename, codetype, timeout)
        if (cid > 0):
            for i in range(0, timeout):
                result = self.result(cid)
                if (result != ''):
                    return cid, result
                else:
                    time.sleep(1)
            return -3003, ''
        else:
            return cid, ''

    def report(self, cid):
        data = {'method': 'report', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'cid': str(cid), 'flag': '0'}
        response = self.request(data)
        if (response):
            return response['ret']
        else:
            return -9001

    def post_url(self, url, fields, files=[]):
        for key in files:
            files[key] = open(files[key], 'rb');
        res = requests.post(url, files=files, data=fields)
        return res.text

######################################################################

# 用戶名(普通用戶)
username    = 'bobo328410948'

# 密碼
password    = 'bobo328410948'                            

# 軟件ID,開發者分成必要參數。登錄開發者后台【我的軟件】獲得!
appid       = 6003                                    

# 軟件密鑰,開發者分成必要參數。登錄開發者后台【我的軟件】獲得!
appkey      = '1f4b564483ae5c907a1d34f8e2f2776c'    

# 圖片文件
filename    = 'code.jpg'                        

# 驗證碼類型,# 例:1004表示4位字母數字,不同類型收費不同。請准確填寫,否則影響識別率。在此查詢所有類型 http://www.yundama.com/price.html
codetype    = 1004

# 超時時間,秒
timeout     = 10                                    

# 檢查
if (username == 'username'):
    print('請設置好相關參數再測試')
else:
    # 初始化
    yundama = YDMHttp(username, password, appid, appkey)

    # 登陸雲打碼
    uid = yundama.login();
    print('uid: %s' % uid)

    # 查詢余額
    balance = yundama.balance();
    print('balance: %s' % balance)

    # 開始識別,圖片路徑,驗證碼類型ID,超時時間(秒),識別結果
    cid, result = yundama.decode(filename, codetype, timeout);
    print('cid: %s, result: %s' % (cid, result))

 

人人網的模擬登錄+cookie

  • 雲打碼驗證碼識別源碼
    • 第一步:引入驗證碼識別方法
    • 第二步:模擬登錄+處理cookie設置源碼
# 定義驗證碼處理方法
def getCodeDate(userName,pwd,codePath,codeType):
    # 用戶名(普通用戶)
    username    = userName

    # 密碼
    password    = pwd                            

    # 軟件ID,開發者分成必要參數。登錄開發者后台【我的軟件】獲得!
    appid       = 6003                                    

    # 軟件密鑰,開發者分成必要參數。登錄開發者后台【我的軟件】獲得!
    appkey      = '1f4b564483ae5c907a1d34f8e2f2776c'    

    # 圖片文件
    filename    = codePath                       

    # 驗證碼類型,# 例:1004表示4位字母數字,不同類型收費不同。請准確填寫,否則影響識別率。在此查詢所有類型 http://www.yundama.com/price.html
    codetype    = codeType

    # 超時時間,秒
    timeout     = 2                                   
    result = None
    # 檢查
    if (username == 'username'):
        print('請設置好相關參數再測試')
    else:
        # 初始化
        yundama = YDMHttp(username, password, appid, appkey)

        # 登陸雲打碼
        uid = yundama.login();
        #print('uid: %s' % uid)

        # 查詢余額
        balance = yundama.balance();
        #print('balance: %s' % balance)

        # 開始識別,圖片路徑,驗證碼類型ID,超時時間(秒),識別結果
        cid, result = yundama.decode(filename, codetype, timeout);
        #print('cid: %s, result: %s' % (cid, result))
    return result

 

#人人網的模擬登錄
import requests
import urllib
from lxml import etree
# 獲取session對象(操作對象是瀏覽器,而不是html頁面),用於處理動態變化的cookie(有cookie的就用session)
session = requests.Session()
#創建連接
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
}
url = 'http://www.renren.com/'
page_text = requests.get(url=url,headers=headers).text

# 創建etree對象xpath定位驗證碼圖片位置,將驗證碼圖片進行下載,持久化存儲
tree = etree.HTML(page_text)
code_img_url = tree.xpath('//*[@id="verifyPic_login"]/@src')[0]
urllib.request.urlretrieve(url=code_img_url,filename='code.jpg')

# 識別驗證碼圖片中的數據值
code_data = getCodeDate('bobo328410948','bobo328410948','./code.jpg',2004)

# 模擬登錄
# 抓包工具找到的登錄時的url
login_url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=201914927558'
data = {
    "email":"www.zhangbowudi@qq.com",
    "icode":code_data,
    "origURL":"http://www.renren.com/home",
    "domain":"renren.com",
    "key_id":"1",
    "captcha_type":"web_login",
    "password":"4f0350f09aeffeef86307747218b214b0960bdf35e30811c0d611fe39db96ec1",
    "rkey":"9e75e8dc3457b14c55a74627fa64fb43",
    "f":"http%3A%2F%2Fwww.renren.com%2F289676607",
}
# 該次請求產生的cookie會被自動存儲到session對象中
session.post(url=login_url,data=data,headers=headers)

#登錄后的url
url = 'http://www.renren.com/289676607/profile'
page_text = session.get(url=url,headers=headers).text

with open('renren.html','w',encoding='utf-8') as fp:
    fp.write(page_text)

 

 

不用抓包工具定義UserAgent的方法(不推薦使用,有時不會生成useragent)

from fake_useragent import UserAgent
ua = UserAgent(verify_ssl=False,use_cache_server=False).random
print(ua)

 

古詩文網模擬登錄
#模擬登錄古詩文網
import requests
import urllib
from lxml import etree
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
}
# 定義session對象用於處理cookie
s = requests.Session()
# 未登錄狀態url
login_url = 'https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx'
page_text = requests.get(url=login_url,headers=headers).text
# 創建etree對象xpath定位驗證碼圖片位置,將驗證碼圖片進行下載,並持久化存儲
tree = etree.HTML(page_text)
img_src = 'https://so.gushiwen.org'+tree.xpath('//*[@id="imgCode"]/@src')[0]
img_data = s.get(url=img_src,headers=headers).content
with open('./img.jpg','wb') as fp:
    fp.write(img_data)
img_text = getCodeDate('bobo328410948','bobo328410948','./img.jpg',1004)

# 模擬登錄
# 登錄后url
url = 'https://so.gushiwen.org/user/login.aspx?from=http%3a%2f%2fso.gushiwen.org%2fuser%2fcollect.aspx'
data = {
    "__VIEWSTATE":"9AsGvh3Je/0pfxId7DYRUi258ayuEG4rrQ1Z3abBgLoDSOeAUatOZOrAIxudqiOauXpR9Zq+dmKJ28+AGjXYHaCZJTTtGgrEemBWI1ed7oS7kpB7Rm/4yma/+9Q=",
    "__VIEWSTATEGENERATOR":"C93BE1AE",
    "from":"http://so.gushiwen.org/user/collect.aspx",
    "email":"www.zhangbowudi@qq.com",
    "pwd":"bobo328410948",
    "code":img_text,# 處理后的驗證碼
    "denglu":"登錄",
}
page_text = s.post(url=url,headers=headers,data=data).text
with open('./gushiwen.html','w',encoding='utf-8') as fp:
    fp.write(page_text)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM