您的位置:首页 > 编程语言 > Python开发

python-57: 验证码登陆源码

2015-12-13 00:00 519 查看
经过前面这么多次的失败,我们也获得了很多知识,得到了很多经验,这时候再不上源码的话就天理不容了

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
__author__ = "217小月月坑"

'''
验证码登陆OK
'''
import urllib
import urllib2
import cookielib

# 网址
Img_URL = 'https://id.ifeng.com/public/authcode'
Login_URL = 'https://id.ifeng.com/api/sitelogin'
Blog_URL = 'http://blog.ifeng.com/16441366.html'

headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0'}

cookieJar = cookielib.CookieJar()
handlers = urllib2.HTTPCookieProcessor(cookieJar)
opener = urllib2.build_opener(handlers)
urllib2.install_opener(opener)
# 向验证码的网址发送请求
img_req=urllib2.Request(Img_URL,headers=headers)
img_response=opener.open(img_req)
print cookieJar
# 文件操作,下载验证码
f = open('/home/ym/code','wb')
f.write(img_response.read())
f.flush()
f.close()
print "验证码图片下载完成"
# 提示用户输入验证码
captcha = raw_input("请输入验证码:")
# 构造post数据
data = {
'u':   '2027598917@qq.com',
'k':   'hp201112701254',
'auth':    captcha,
'auto':    'on',
'comfrom':'',
'type':    '2',
}
post_data = urllib.urlencode(data)

# 将post 信息发送到接受信息的网址,登陆
login_req = urllib2.Request(Login_URL,post_data)
login_response = opener.open(login_req)
print cookieJar
blog_response = opener.open(Blog_URL)
print cookieJar
print blog_response.read()

好了,看看登陆成功之后返回的是什么



就是这么简单的几行代码,OK,这个实例到这里就结束啦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 爬虫