python爬蟲--運用cookie類比登入知乎

來源:互聯網
上載者:User

標籤:password   find   file   爬蟲   ignore   gen   turn   介紹   --   

前面已經介紹過,運用表單填寫帳號,使用者名稱的方式類比登入知乎。若登入成功,則之後就可以利用cookie登入,無需重複之前步驟。

import requestsimport http.cookiejarfrom bs4 import BeautifulSoupsession = requests.Session()session.cookies = http.cookiejar.LWPCookieJar("cookie")agent = ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/5.1.2.3000 Chrome/55.0.2883.75 Safari/537.36‘headers = {    "Host": "www.zhihu.com",    "Origin":"https://www.zhihu.com/",    "Referer":"http://www.zhihu.com/",    ‘User-Agent‘:agent}postdata = {    ‘password‘: ‘*******‘,  #填寫密碼    ‘account‘: ‘********‘, #填寫帳號}response = session.get("https://www.zhihu.com", headers=headers)soup = BeautifulSoup(response.content, "html.parser")xsrf = soup.find(‘input‘, attrs={"name": "_xsrf"}).get("value")postdata[‘_xsrf‘] =xsrfresult = session.post(‘http://www.zhihu.com/login/email‘, data=postdata, headers=headers)session.cookies.save(ignore_discard=True, ignore_expires=True)

運行後,在代碼所在檔案夾中出現cookie檔案。

現在載入cookie登入:

import requestsimport http.cookiejar as cookielibsession = requests.session()session.cookies = cookielib.LWPCookieJar(filename=‘cookie‘)try:    session.cookies.load(ignore_discard=True)except:       print("Cookie 未能載入")def isLogin():    url = "https://www.zhihu.com/"    login_code = session.get(url, headers=headers, allow_redirects=False).status_code    if login_code == 200:        return True    else:        return Falseif __name__ == ‘__main__‘:    agent = ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/5.1.2.3000 Chrome/55.0.2883.75 Safari/537.36‘    headers = {        "Host": "www.zhihu.com",        "Origin": "https://www.zhihu.com/",        "Referer": "http://www.zhihu.com/",        ‘User-Agent‘: agent    }    if isLogin():        print(‘您已經登入‘)

運行後顯示:您已經登入。

 

cookielib模組的主要作用是提供可儲存cookie的對象,以便於requests模組配合使用來訪問Internet資源。Cookielib模組非常強大,我們可以利用本模組的CookieJar類的對象來捕獲cookie並在後續串連請求時重新發送,比如可以實現類比登入功能。該模組主要的對象有CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar。

它們的關係:CookieJar —-派生—->FileCookieJar  —-派生—–>MozillaCookieJar和LWPCookieJar

預設的是FileCookieJar沒有實現save函數。

而MozillaCookieJar或LWPCookieJar都已經實現了。

所以可以用MozillaCookieJar或LWPCookieJar,去自動實現cookie的save。

CookieJar                       

                            /    

            FileCookieJar      

             /                   \    

 MozillaCookieJar      LWPCookieJar       

python爬蟲--運用cookie類比登入知乎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.