爬蟲知乎登陸

爬蟲入門

功能:
知乎算是對爬蟲比較友好的網(wǎng)站了,但是!
現(xiàn)在登陸驗證碼很惡心,需要點擊圖中倒立的文字!這讓我們這種本來識字就不多的人情何以堪/(ㄒoㄒ)/~~。于是采用替換url參數(shù)的方法,換個登陸驗證碼登陸,驗證碼需要手動輸入。

#coding=utf-8
import urllib2
import re
from bs4 import BeautifulSoup
import requests
import time

url = "https://www.zhihu.com/#signin"
requests.adapters.DEFAULT_RETRIES = 511
###
定義函數(shù),輸出驗證碼
###

def captcha(captcha_data):
    with open("captcha.jpg","wb")as f:
        f.write(captcha_data)
    text = raw_input("請輸入驗證碼:")
    return text

###
通過抓包可以發(fā)現(xiàn),驗證碼圖片是由unix時間戳生成的,于是我們可以自己抓出登陸時的四位數(shù)字字母驗證碼
###
def zhihulogin():
    while True:
        try:
            sess = requests.Session()
            sess.keep_alive = False
            headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}

            html = sess.get(url,headers = headers).text
            bs = BeautifulSoup(html,"lxml")

            _xsrf = bs.find("input",attrs={"name":"_xsrf"}).get("value")

            captcha_url = "https://www.zhihu.com/captcha.gif?r=%d&type=login" %(time.time() * 1000)

            captcha_data = sess.get(captcha_url,headers =headers).content
            text = captcha(captcha_data)
            data = {
                "_xsrf":_xsrf,
                "email":email,
                "password":pwd,
                "captcha":text
            }

            response = sess.post("https://www.zhihu.com/login/email",data = data,headers = headers)
            print response.text
            print captcha_url

            print _xsrf
            break
        except:
###
這里不加sleep的話,好像會報ssl最大連接數(shù)的錯誤,具體的錯誤日志忘了(lll¬ω¬)
###
            time.sleep(5)


if __name__ == "__main__":
    zhihulogin()

結(jié)束語

執(zhí)行時需要把腳本里面的用戶名和密碼換成有效的,然后執(zhí)行腳本,打開抓出的圖片,輸入驗證碼,就可以登陸知乎啦

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

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

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