Python 爬虫模拟登陆知乎

# -*- 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保存到文件里








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值