模擬登錄國內著名知識交流網站

以前看了很長時間的前端相關知識,怕python手生,寫個模擬登錄恢復一下html

zhihu網上的info有些是須要登錄後才能訪問爬去的,因此不妨試一試前端

1 首先本身登錄,而後用fiddler進行抓包python

發現登錄zhihu須要post如下data:web

A?, 驗證碼哪去了,算了,沒有更好。json

下面就要編寫代碼了,稍等,先看一下zhihu的responsecookie

resp的類型是json格式,通過檢查,msg的值就是咱們的登陸狀態了,因此一會咱們會打印出這個值證實是否登陸。session

2 下面就很少說了,直接上代碼app

#!/usr/bin/python
# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
import cookielib
import json

HomePage = 'https://www.zXXXu.com/' # 主頁網址
# = r'zhihu_cookies.txt'

session = requests.session()

cookie = cookielib.CookieJar()  #這個方法能夠暫存cookie
'''
session.cookies = cookielib.MozillaCookieJar(filename)  #這個方法是將cookie放入文件中
try:
    session.cookies.load(filename=filename, ignore_discard=True, ignore_expirex=True)  #gnore_discard的意思是即便cookies將被丟棄也將它保存下來,ignore_expires的意思是若是在該文件中cookies已經存在,則覆蓋原文件寫入,
except:
    print 'Cookie can not load!'
'''

headers = {'Connection': 'keep-alive',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
            'Accept-Encoding': 'gzip, deflate, sdch',
            'Host': 'www.zXXXu.com',
           }



def get_xsrf():
    text = session.get(HomePage, headers=headers).text
    soup = BeautifulSoup(text, 'html.parser')
    result = soup.find('div', class_='view view-signin').find('input')['value']
    return result


#獲取驗證碼
def get_captcha():
    pass


def login_zhihu(phone, passwd):
    login_url = HomePage+'/login/phone_num'
    data = {
        '_xsrf': '%s' % get_xsrf(),
        'password': passwd,
        'phone_num': phone,
        'captcha_type': 'cn'
    }
    result = session.post(login_url, data=data, headers=headers)
    print json.loads(result.text)['msg']  # result的body是son格式,而'msg'的值是登陸狀態
    return


if __name__ == '__main__':
    phone = raw_input('Please input phone_num: ')
    passwd = raw_input('Please input password: ')
    url = HomePage + '/settings/profile'   # 登陸後才能夠訪問本身的profile
    login_zhihu(phone, passwd)
    resp_status = session.get(url, headers=headers, allow_redirects=False).status_code  # 此處關閉了跳轉的操做
    print resp_status  # 返回結果是訪問狀態碼

裏面有兩點須要說明post

2.1 cookie的處理,我用了一個cookiejar存儲了cookie,你們這步也能夠忽略。url

2.2 headers必定要寫全,以前改個UA就能登陸了,如今須要都寫上才能夠,zhihu也是反爬上掙扎(我但是在這裏辛辛苦苦試了不少遍才察覺出來,你們不要像我這麼傻)

 

3 最後就是返回的結果了

 

最後最後給你們推薦一個jianshu的做者寫的zhihu爬蟲,它的裏面包括處理驗證碼(我是真的很煩手動輸入)連接地址

相關文章
相關標籤/搜索