溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何利用Python實(shí)現(xiàn)模擬登錄知乎

發(fā)布時(shí)間:2022-05-25 13:50:23 來(lái)源:億速云 閱讀:204 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“如何利用Python實(shí)現(xiàn)模擬登錄知乎”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“如何利用Python實(shí)現(xiàn)模擬登錄知乎”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。

環(huán)境與開(kāi)發(fā)工具

在抓包的時(shí)候,開(kāi)始使用的是Chrome開(kāi)發(fā)工具中的Network,結(jié)果沒(méi)有抓到,后來(lái)使用Fiddler成功抓取數(shù)據(jù)。下面逐步來(lái)細(xì)化上述過(guò)程。

模擬知乎登錄前,先看看本次案例使用的環(huán)境及其工具:

  • Windows 7 + Python 2.75

  • Chrome + Fiddler: 用來(lái)監(jiān)控客戶端與服務(wù)器的通訊情況,以及查找相關(guān)參數(shù)的位置。

模擬過(guò)程概述

  • 使用Google瀏覽器結(jié)合Fiddler來(lái)監(jiān)控客戶端與服務(wù)端的通訊過(guò)程;

  • 根據(jù)監(jiān)控結(jié)果,構(gòu)造請(qǐng)求服務(wù)器過(guò)程中傳遞的參數(shù);

  • 使用Python模擬參數(shù)傳遞過(guò)程。

客戶端與服務(wù)端通信過(guò)程的幾個(gè)關(guān)鍵點(diǎn):

  • 登錄時(shí)的url地址。

  • 登錄時(shí)提交的參數(shù)【params】,獲取方式主要有兩種:第一、分析頁(yè)面源代碼,找到表單標(biāo)簽及屬性。適應(yīng)比較簡(jiǎn)單的頁(yè)面。第二、使用抓包工具,查看提交的url和參數(shù),通常使用的是Chrome的開(kāi)發(fā)者工具中的Network, Fiddler等。

  • 登錄后跳轉(zhuǎn)的url。

參數(shù)探索

首先看看這個(gè)登錄頁(yè)面,也就是我們登錄時(shí)的url地址。

如何利用Python實(shí)現(xiàn)模擬登錄知乎

看到這個(gè)頁(yè)面,我們也可以大概猜測(cè)下請(qǐng)求服務(wù)器時(shí)傳遞了幾個(gè)字段,很明顯有:用戶名、密碼、驗(yàn)證碼以及“記住我”這幾個(gè)值。那么實(shí)際上有哪些呢?下面來(lái)分分析下。

首先查看一下HTML源碼,Google里可以使用CTRL+U查看,然后使用CTRL+F輸入input看看有哪些字段值,詳情如下:

如何利用Python實(shí)現(xiàn)模擬登錄知乎

通過(guò)源碼,我們可以看到,在請(qǐng)求服務(wù)器的過(guò)程中還攜帶了一個(gè)隱藏字段”_xsrf”。那么現(xiàn)在的問(wèn)題是:這些參數(shù)在傳遞時(shí)是以什么名字傳遞的呢?這就需要借用其他工具抓包進(jìn)行分析了。筆者是Windows系統(tǒng),這里使用的是Fiddler(當(dāng)然,你也可以使用其他的)。

抓包過(guò)程比較繁瑣,因?yàn)樽サ降臇|西比較多,很難快速的找到需要的信息。關(guān)于fiddler,很容易使用,有過(guò)不會(huì),可以去百度搜一下。為了防止其他信息干擾,我們先將fiddler中的記錄清除,然后輸入用戶名(筆者使用的是郵箱登錄)、密碼等信息登錄,相應(yīng)的在fiddler中會(huì)有如下結(jié)果:

如何利用Python實(shí)現(xiàn)模擬登錄知乎

備注:如果是使用手機(jī)登錄,則對(duì)應(yīng)fiddler中的url是“/login/phone_num”。

為了查看詳細(xì)的請(qǐng)求參數(shù),我們左鍵單機(jī)“/login/email”,可以看到下列信息:

如何利用Python實(shí)現(xiàn)模擬登錄知乎

請(qǐng)求方式為POST,請(qǐng)求的url為https://www.zhihu.com/login/email。而從From Data可以看出,相應(yīng)的字段名稱如下:

  • _xsrf

  • captcha

  • email

  • password

  • remember

對(duì)于這五個(gè)字段,代碼中email、password以及captcha都是手動(dòng)輸入的,remember初始化為true。剩下的_xsrf則可以根據(jù)登錄頁(yè)面的源文件,取input為_(kāi)xsrf的value值即可。

如何利用Python實(shí)現(xiàn)模擬登錄知乎

對(duì)于驗(yàn)證碼,則需要通過(guò)額外的請(qǐng)求,該鏈接可以通過(guò)定點(diǎn)查看源碼看出:

如何利用Python實(shí)現(xiàn)模擬登錄知乎

鏈接為https://www.zhihu.com/captcha.gif?type=login,這里省略了ts(經(jīng)測(cè)試,可省略掉)?,F(xiàn)在,可以使用代碼進(jìn)行模擬登錄。

溫馨提示:如果使用的是手機(jī)號(hào)碼進(jìn)行登錄,則請(qǐng)求的url為https://www.zhihu.com/login/phone_num,同時(shí)email字段名稱將變成“phone_num”。

模擬源碼

在編寫(xiě)代碼實(shí)現(xiàn)知乎登錄的過(guò)程中,筆者將一些功能封裝成了一個(gè)簡(jiǎn)單的類(lèi)WSpider,以便復(fù)用,文件名稱為WSpider.py。

# -*- coding: utf-8 -*-
"""
Created on Thu Nov 02 14:01:17 2016
@author: liudiwei
"""
import urllib
import urllib2
import cookielib
import logging  

class WSpider(object):
    def __init__(self):
        #init params
        self.url_path = None
        self.post_data = None
        self.header = None
        self.domain = None
        self.operate = None

        #init cookie
        self.cookiejar = cookielib.LWPCookieJar()
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookiejar))
        urllib2.install_opener(self.opener)

    def setRequestData(self, url_path=None, post_data=None, header=None):
        self.url_path = url_path
        self.post_data = post_data
        self.header = header

    def getHtmlText(self, is_cookie=False):
        if self.post_data == None and self.header == None:
            request = urllib2.Request(self.url_path)
        else:
            request = urllib2.Request(self.url_path, urllib.urlencode(self.post_data), self.header)
        response = urllib2.urlopen(request)
        if is_cookie: 
            self.operate = self.opener.open(request)
        resText = response.read()
        return resText

    """
    Save captcha to local    
    """    
    def saveCaptcha(self, captcha_url, outpath, save_mode='wb'):
        picture = self.opener.open(captcha_url).read() #用openr訪問(wèn)驗(yàn)證碼地址,獲取cookie
        local = open(outpath, save_mode)
        local.write(picture)
        local.close()    

    def getHtml(self, url):
        page = urllib.urlopen(url)
        html = page.read()
        return html


    """
    功能:將文本內(nèi)容輸出至本地
    @params
        content:文本內(nèi)容
        out_path: 輸出路徑
    """
    def output(self, content, out_path, save_mode="w"):
        fw = open(out_path, save_mode)
        fw.write(content)
        fw.close()
        
    """#EXAMPLE
    logger = createLogger('mylogger', 'temp/logger.log')
    logger.debug('logger debug message')  
    logger.info('logger info message')  
    logger.warning('logger warning message')  
    logger.error('logger error message')  
    logger.critical('logger critical message')  
    """    
    def createLogger(self, logger_name, log_file):
        # 創(chuàng)建一個(gè)logger
        logger = logging.getLogger(logger_name)  
        logger.setLevel(logging.INFO)  

        # 創(chuàng)建一個(gè)handler,用于寫(xiě)入日志文件    
        fh = logging.FileHandler(log_file)  

        # 再創(chuàng)建一個(gè)handler,用于輸出到控制臺(tái)    
        ch = logging.StreamHandler()  
        # 定義handler的輸出格式formatter    

        formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s | %(message)s')  
        fh.setFormatter(formatter)  
        ch.setFormatter(formatter)  
        # 給logger添加handler    

        logger.addHandler(fh)  
        logger.addHandler(ch)  
        return logger

關(guān)于模擬登錄知乎的源碼,保存在zhiHuLogin.py文件,內(nèi)容如下:

# -*- coding: utf-8 -*-
"""
Created on Thu Nov 02 17:07:17 2016
@author: liudiwei

"""
import urllib
from WSpider import WSpider
from bs4 import BeautifulSoup as BS
import getpass
import json
import WLogger as WLog
"""
2016.11.03 由于驗(yàn)證碼問(wèn)題暫時(shí)無(wú)法正常登陸
2016.11.04 成功登錄,期間出現(xiàn)下列問(wèn)題
驗(yàn)證碼錯(cuò)誤返回:{ "r": 1, "errcode": 1991829, "data": {"captcha":"驗(yàn)證碼錯(cuò)誤"}, "msg": "驗(yàn)證碼錯(cuò)誤" }
驗(yàn)證碼過(guò)期:{ "r": 1, "errcode": 1991829, "data": {"captcha":"驗(yàn)證碼回話無(wú)效 :(","name":"ERR_VERIFY_CAPTCHA_SESSION_INVALID"}, "msg": "驗(yàn)證碼回話無(wú)效 :(" }
登錄:{"r":0, "msg": "登錄成功"}
"""
def zhiHuLogin():
    spy = WSpider()
    logger = spy.createLogger('mylogger', 'temp/logger.log')
    homepage = r"https://www.zhihu.com/"    
    html = spy.opener.open(homepage).read()
    soup = BS(html, "html.parser")
    _xsrf = soup.find("input", {'type':'hidden'}).get("value")

    #根據(jù)email和手機(jī)登陸得到的參數(shù)名不一樣,email登陸傳遞的參數(shù)是‘email',手機(jī)登陸傳遞的是‘phone_num'
    username = raw_input("Please input username: ")
    password = getpass.getpass("Please input your password: ")
    account_name = None
    if "@" in username:
        account_name = 'email'
    else:
        account_name = 'phone_num' 

    #保存驗(yàn)證碼
    logger.info("save captcha to local machine.")
    captchaURL = r"https://www.zhihu.com/captcha.gif?type=login" #驗(yàn)證碼url
    spy.saveCaptcha(captcha_url=captchaURL, outpath="temp/captcha.jpg") #temp目錄需手動(dòng)創(chuàng)建

    #請(qǐng)求的參數(shù)列表
    post_data = {
        '_xsrf': _xsrf,
        account_name: username,
        'password': password,
        'remember_me': 'true',
        'captcha':raw_input("Please input captcha: ")

    }

    #請(qǐng)求的頭內(nèi)容
    header ={
        'Accept':'*/*' ,
        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With':'XMLHttpRequest',
        'Referer':'https://www.zhihu.com/',
        'Accept-Language':'en-GB,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
        'Accept-Encoding':'gzip, deflate, br',
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
        'Host':'www.zhihu.com'
    }

    url = r"https://www.zhihu.com/login/" + account_name
    spy.setRequestData(url, post_data, header)
    resText = spy.getHtmlText()
    jsonText = json.loads(resText)

    if jsonText["r"] == 0:
        logger.info("Login success!")
    else:
        logger.error("Login Failed!")
        logger.error("Error info ---> " + jsonText["msg"])

    text = spy.opener.open(homepage).read() #重新打開(kāi)主頁(yè),查看源碼可知此時(shí)已經(jīng)處于登錄狀態(tài)
    spy.output(text, "out/home.html") #out目錄需手動(dòng)創(chuàng)建

if __name__ == '__main__':
    zhiHuLogin()

關(guān)于源碼的分析,可以參考代碼中的注解。

運(yùn)行結(jié)果

在控制臺(tái)中運(yùn)行python zhiHuLogin.py,然后按提示輸入相應(yīng)的內(nèi)容,最后可得到以下不同的結(jié)果(舉了三個(gè)實(shí)例):

結(jié)果一:密碼錯(cuò)誤

如何利用Python實(shí)現(xiàn)模擬登錄知乎

結(jié)果二:驗(yàn)證碼錯(cuò)誤

如何利用Python實(shí)現(xiàn)模擬登錄知乎

結(jié)果三:成功登錄

如何利用Python實(shí)現(xiàn)模擬登錄知乎

讀到這里,這篇“如何利用Python實(shí)現(xiàn)模擬登錄知乎”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI