标签:
这是一个模拟登录知乎的爬虫。运行后输入用户名密码以及和程序同一目录下的验证码图片,登陆成功后能够显示你在豆瓣地昵称。
#! /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()
鸣谢:志立
标签:
原文地址:http://www.cnblogs.com/wuyouwulv/p/python_webcrawler_sample.html