# -*- coding:utf-8 -*- import cookielib import urllib import urllib2 import re url_start = r'https://www.zhihu.com/topic/19556498/questions?page=' filename = 'cookie.txt' cookie = cookielib.MozillaCookieJar(filename) handler = urllib2.HTTPCookieProcessor(cookie) opener = urllib2.build_opener(handler) opener.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.3.0')] def login(): handler = urllib2.HTTPCookieProcessor(cookie) opener = urllib2.build_opener(handler) opener.addheaders = [ ('User-agent', 'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.3.0')] username = '13923858795' password = '625124155' cap_url = 'https://www.zhihu.com/captcha.gif?r=1466595391805&type=login' cap_content = urllib2.urlopen(cap_url).read()#抓取指定网页 cap_file = open('./cap.gif','wb')#访问非文本格式文件(二进制文件) cap_file.write(cap_content) cap_file.close() captcha = raw_input('capture:') url = 'https://www.zhihu.com/login/phone_num' data = urllib.urlencode({"phone_num":username,"password":password,"captcha":captcha}) print urllib2.urlopen(url,data).read() response = opener.open('http://www.zhihu.com') cookie.save(ignore_discard=True, ignore_expires=True) for item in cookie: print 'Name = ' + item.name print 'Value = ' + item.value if __name__ == "__main__": login()
以上就能正常登陆 外加获取到知乎的cook,并将cook保存到文件里