python模拟登录知乎
2015-10-11 22:51
609 查看
这是一个模拟登录知乎的爬虫。运行后输入用户名密码以及和程序同一目录下的验证码图片,登陆成功后能够显示你在豆瓣地昵称。
鸣谢:志立
#! /usr/bin/env python #! -*-coding: utf-8 -*- import json import urllib import urllib2 import cookielib class Zhihu_login(object): """登陆知乎的一个演示程序""" def __init__(self): self.test_url = "http://www.zhihu.com/topic" self.login_url = "http://www.zhihu.com/login/email" self.checkcode_url = "http://www.zhihu.com/captcha.gif" """创建一个带cookie的opener""" cj = cookielib.CookieJar() self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)); def getCheckCode(self): """获取验证码, 保存在当前目录下""" pic = open("checkcode.gif", "w") """ 验证码一定要用self.opener打开, 因为服务器需要检验cookie是否与当前提交的验证码匹配, opener请求的时候可以将cookie一起发过去。 """ resp = self.opener.open(self.checkcode_url) print >> pic, resp.read() pic.close() def login(self): post_data = {} post_data["email"] = raw_input("输入用户名:\n") post_data["password"] = raw_input("输入密码:\n") self.getCheckCode() info = raw_input("输入验证码,看不清输入'?'再换一张\n") while(info == '?'): self.getCheckCode() info = raw_input("输入验证码,看不清输入'?'再换一张\n") post_data["captcha"] = info post_data = urllib.urlencode(post_data) resp = self.opener.open(self.login_url, post_data) status = json.loads(resp.read()) if status["r"] == 0: print "登陆成功!" print json.dumps(status, ensure_ascii=False).encode("utf-8", "ignore") #print "开始测试。。。" #self.test() else: print "登录失败!" print "失败信息如下:" print json.dumps(status, ensure_ascii=False).encode("utf-8", "ignore") def test(self): """看看是否能在源代码里面查找到你的知乎名字,如果能说明确实成功了。""" resp = self.opener.open(self.test_url) print resp.read() if __name__ == "__main__": Zhihu_login().login()
鸣谢:志立
相关文章推荐
- Python Scapy(2.3.1)文档学习(六):添加新的协议
- Python 流程控制
- python 面向对象编程
- 【Python之旅】第六篇(五):生产者消费者模型实现多线程异步交互
- 【Python之旅】第六篇(五):生产者消费者模型实现多线程异步交互
- Python 快速入门
- [每日一答] [20151011] 如何在Python2.7版本中安装pip程序呢?
- python 初步实现人机对话
- python unix 时间戳
- 【Python】if语句使用规则
- 【Python】Learn Python the hard way, ex35 通过一个简单游戏,练习循环和分支语句
- Python运维编程
- 【Python之旅】第六篇(四):Python多线程锁
- 【Python之旅】第六篇(四):Python多线程锁
- python中的矩阵运算
- 【Python】Learn Python the hard way, ex33 while循环
- 【Python】Learn Python the hard way, ex32 for循环
- 【Python】Learn Python the hard way, ex29 if语句
- 【Python之旅】第六篇(三):Python多线程及其使用方法
- 【Python】Learn Python the hard way, ex26 修改代码错误