Python爬蟲學(xué)習(xí)15-Requests模擬登陸知乎

一、常見(jiàn)狀態(tài)碼

表達(dá)式 說(shuō)明
200 請(qǐng)求被正確執(zhí)行
301/302 永久性重定向/臨時(shí)性重定向
403 沒(méi)有權(quán)限訪問(wèn)
404 沒(méi)有資源訪問(wèn)
500 服務(wù)器錯(cuò)誤
503 服務(wù)器停機(jī)或正在維護(hù)

二、登錄分析

在登錄界面輸入手機(jī)號(hào)和帳號(hào)

Paste_Image.png

返回的地址為
Request URL:https://www.zhihu.com/login/phone_num
當(dāng)輸入email地址后返回的地址為
Request URL:https://www.zhihu.com/login/email
并且在formdata中出現(xiàn)
_xsrf:a71f46d549979fa192c09e11e4a463b5這樣的字符串。

Paste_Image.png

三、抓取xsrf的值

正則匹配抓取xsrf需要使用header頭來(lái)進(jìn)行源代碼的獲取

def get_xsrf():
    response = requests.get("https://www.zhihu.com", headers=headers)
    re_match = re.match('.*name="_xsrf" value="(.*)"/>', response.text, re.S)
    return re_match

其中re.S,可以換行匹配。

四、登錄邏輯

import http.cookiejar as cookielib

def get_xsrf():
    response = requests.get("https://www.zhihu.com", headers=headers)
    re_match = re.match('.*name="_xsrf" value="(.*)"/>', response.text, re.S)
    if re_match:
        return re_match.group(1)
    else:
        return ""

session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename="cookies.txt")
try:
    session.cookies.load(ignore_discard=True)
except:
    print("Cookie未能加載")

def zhihu_login(account, password):
    if re.match("^1\d{10}", account):
        print("手機(jī)號(hào)碼登錄")
        post_url = "https://www.zhihu.com/login/phone_num"
        post_data = {
            "_xsrf": get_xsrf(),
            "phone_num": account,
            "password": password,
            "captcha": get_captcha(),
        }
    else:
        print("郵箱登錄")
        post_url = "https://www.zhihu.com/login/email"
        post_data = {
            "_xsrf": get_xsrf(),
            "email": account,
            "password": password,
            "captcha": get_captcha(),
        }
    response_text = session.post(post_url, data=post_data, headers=headers)
    session.cookies.save()

以上代碼是通過(guò)引入requests庫(kù),使用它的session方法,進(jìn)行連接,構(gòu)造post_data,把自己的用戶名密碼等信息發(fā)送到網(wǎng)站,并通過(guò)正則判斷發(fā)送的是郵箱或是手機(jī)進(jìn)行登錄。
引入import http.cookiejar as cookielib,通過(guò)session.cookies.save(),對(duì)cookie進(jìn)行保存。

五、獲得驗(yàn)證碼

def get_captcha():
    import time
    t = str(int(time.time()*1000))
    captcha_url = "https://www.zhihu.com/captcha.gif?r={}&type=login".format(t)
    t = session.get(captcha_url, headers=headers)
    with open('captpcha.jpg', 'wb') as f:
        f.write(t.content)
        f.close()
    from PIL import Image
    try:
        im = Image.open('captpcha.jpg')
        im.show()
        im.close()
    except:
        pass
    captcha = input("輸入驗(yàn)證碼")
    return captcha

通過(guò) 上面的代碼獲得驗(yàn)證碼并使用圖片顯示的方法查看輸入。

六、不重新登錄

登錄只能一次,如果再次登錄,可以直接通過(guò)查看cookie來(lái)判斷是否為登錄狀態(tài)。

session.cookies = cookielib.LWPCookieJar(filename="cookies.txt")
try:
    session.cookies.load(ignore_discard=True)
except:
    print("Cookie未能加載")

def is_login():
    inbox_url = "https://www.zhihu.com/index"
    response = session.get(inbox_url, headers=headers, allow_redirects=False)
    if response.status_code != 200:
        return "失敗"
    else:
        return "成功"

首先把cookie通過(guò)session.cookies.load裝載進(jìn)來(lái),執(zhí)行is_login()函數(shù),如果成功可以訪問(wèn)inbox_url頁(yè)面,則狀態(tài)碼為200表示成功。這里一定要注意allow_redirects=False,當(dāng)不允許且登錄時(shí)會(huì)自動(dòng)跳轉(zhuǎn)到登錄頁(yè)面,則狀態(tài)碼是301或者302。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容