python requests cookie

397 查看


#encoding=utf8
import requests,time
#登录知乎后通过document.cookie获取cookie
cookie = '_zap=78503ecc-9420-482c-a747-5761a7c9de8c; _za=de220e47-6e79-4c2d-80c6-74a86eb567ce; _ga=GA1.2.932820854.1429357203; udid="xxxxxxxxxxx";'
Default_Header = {'X-Requested-With': 'XMLHttpRequest',
                  'Referer': 'http://www.zhihu.com',
                  'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; '
                                'rv:39.0) Gecko/20100101 Firefox/39.0',
                  'Host': 'www.zhihu.com',
                  'Cookie':cookie}
_session = requests.session()
_session.headers.update(Default_Header)
header = {'X-Requested-With': 'XMLHttpRequest',
                  'Referer': 'http://www.zhihu.com',
                  'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; '
                                'rv:39.0) Gecko/20100101 Firefox/39.0',
                  'Host': 'www.zhihu.com'}

url = 'https://www.zhihu.com/noti7/stack/default?limit=10&r=1473558020498' 
cookies={} 
for line in cookie.split(';'): 
    name,value=line.strip().split('=',1) 
    cookies[name]=value
#r = requests.get(url, headers=Default_Header) 
r = requests.get(url, headers=header,cookies=cookies) 
#r = _session.get(url) 
#print(r.content)
#print(cookies)
print(r.json())

#模拟登录
def login():
    '''登录知乎'''
    username = 'xxx'
    password = 'xxx'
    cap_content = _session.get('https://www.zhihu.com/captcha.gif?r='+str(int(time.time())*1000)+'&type=login').content
    cap_file = open('cap.gif','wb')
    cap_file.write(cap_content)
    cap_file.close()
    captcha = input('capture:')
    data = {"email":username,"password":password,"captcha":captcha}
    r = _session.post('https://www.zhihu.com/login/email', data)
    print ((r.json())['msg'])