python爬虫豆瓣网的模拟登录实现


Posted in Python onAugust 21, 2019

思路

一、想要实现登录豆瓣关键点

分析真实post地址 ----寻找它的formdata,如下图,按浏览器的F12可以找到。

python爬虫豆瓣网的模拟登录实现

实战操作

  • 实现:模拟登录豆瓣,验证码处理,登录到个人主页就算是success
  • 数据:没有抓取数据,此实战主要是模拟登录和处理验证码的学习。要是有需求要抓取数据,编写相关的抓取规则即可抓取内容。

登录成功展示如图:

python爬虫豆瓣网的模拟登录实现

spiders文件夹中DouBan.py主要代码如下:

# -*- coding: utf-8 -*-
import scrapy,urllib,re
from scrapy.http import Request,FormRequest
import ruokuai
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
class DoubanSpider(scrapy.Spider):
 name = "DouBan"
 allowed_domains = ["douban.com"]
 #start_urls = ['http://douban.com/']
 header={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"} #供登录模拟使用
 def start_requests(self):
  url='https://www.douban.com/accounts/login'
  return [Request(url=url,meta={"cookiejar":1},callback=self.parse)]#可以传递一个标示符来使用多个。如meta={'cookiejar': 1}这句,后面那个1就是标示符

 def parse(self, response):
  captcha=response.xpath('//*[@id="captcha_image"]/@src').extract() #获取验证码图片的链接
  print captcha
  if len(captcha)>0:
   '''此时有验证码'''
   #人工输入验证码
   #urllib.urlretrieve(captcha[0],filename="C:/Users/pujinxiao/Desktop/learn/douban20170405/douban/douban/spiders/captcha.png")
   #captcha_value=raw_input('查看captcha.png,有验证码请输入:')

   #用快若打码平台处理验证码--------验证码是任意长度字母,成功率较低
   captcha_value=ruokuai.get_captcha(captcha[0])
   reg=r'<Result>(.*?)</Result>'
   reg=re.compile(reg)
   captcha_value=re.findall(reg,captcha_value)[0]
   print '验证码为:',captcha_value

   data={
    "form_email": "weisuen007@163.com",
    "form_password": "weijc7789",
    "captcha-solution": captcha_value,
    #"redir": "https://www.douban.com/people/151968962/",  #设置需要转向的网址,由于我们需要爬取个人中心页,所以转向个人中心页
   }
  else:
   '''此时没有验证码'''
   print '无验证码'
   data={
    "form_email": "weisuen007@163.com",
    "form_password": "weijc7789",
    #"redir": "https://www.douban.com/people/151968962/",
   }
  print '正在登陆中......'
  ####FormRequest.from_response()进行登陆
  return [
   FormRequest.from_response(
    response,
    meta={"cookiejar":response.meta["cookiejar"]},
    headers=self.header,
    formdata=data,
    callback=self.get_content,
   )
  ]
 def get_content(self,response):
  title=response.xpath('//title/text()').extract()[0]
  if u'登录豆瓣' in title:
   print '登录失败,请重试!'
  else:
   print '登录成功'
   '''
   可以继续后续的爬取工作
   '''

ruokaui.py代码如下:

我所用的是若块打码平台,选择url识别验证码,直接给打码平台验证码图片的链接地址,传回验证码的值。

# -*- coding: utf-8 -*-
import sys, hashlib, os, random, urllib, urllib2
from datetime import *
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
class APIClient(object):
 def http_request(self, url, paramDict):
  post_content = ''
  for key in paramDict:
   post_content = post_content + '%s=%s&'%(key,paramDict[key])
  post_content = post_content[0:-1]
  #print post_content
  req = urllib2.Request(url, data=post_content)
  req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) 
  response = opener.open(req, post_content) 
  return response.read()

 def http_upload_image(self, url, paramKeys, paramDict, filebytes):
  timestr = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  boundary = '------------' + hashlib.md5(timestr).hexdigest().lower()
  boundarystr = '\r\n--%s\r\n'%(boundary)
  
  bs = b''
  for key in paramKeys:
   bs = bs + boundarystr.encode('ascii')
   param = "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s"%(key, paramDict[key])
   #print param
   bs = bs + param.encode('utf8')
  bs = bs + boundarystr.encode('ascii')
  
  header = 'Content-Disposition: form-data; name=\"image\"; filename=\"%s\"\r\nContent-Type: image/gif\r\n\r\n'%('sample')
  bs = bs + header.encode('utf8')
  
  bs = bs + filebytes
  tailer = '\r\n--%s--\r\n'%(boundary)
  bs = bs + tailer.encode('ascii')
  
  import requests
  headers = {'Content-Type':'multipart/form-data; boundary=%s'%boundary,
     'Connection':'Keep-Alive',
     'Expect':'100-continue',
     }
  response = requests.post(url, params='', data=bs, headers=headers)
  return response.text

def arguments_to_dict(args):
 argDict = {}
 if args is None:
  return argDict
 
 count = len(args)
 if count <= 1:
  print 'exit:need arguments.'
  return argDict
 
 for i in [1,count-1]:
  pair = args[i].split('=')
  if len(pair) < 2:
   continue
  else:
   argDict[pair[0]] = pair[1]

 return argDict

def get_captcha(image_url):
 client = APIClient()
 while 1:
  paramDict = {}
  result = ''
  act = raw_input('请输入打码方式url:')
  if cmp(act, 'info') == 0: 
   paramDict['username'] = raw_input('username:')
   paramDict['password'] = raw_input('password:')
   result = client.http_request('http://api.ruokuai.com/info.xml', paramDict)
  elif cmp(act, 'register') == 0:
   paramDict['username'] = raw_input('username:')
   paramDict['password'] = raw_input('password:')
   paramDict['email'] = raw_input('email:')
   result = client.http_request('http://api.ruokuai.com/register.xml', paramDict)
  elif cmp(act, 'recharge') == 0:
   paramDict['username'] = raw_input('username:')
   paramDict['id'] = raw_input('id:')
   paramDict['password'] = raw_input('password:')
   result = client.http_request('http://api.ruokuai.com/recharge.xml', paramDict)
  elif cmp(act, 'url') == 0:
   paramDict['username'] = '********'
   paramDict['password'] = '********'
   paramDict['typeid'] = '2000'
   paramDict['timeout'] = '90'
   paramDict['softid'] = '76693'
   paramDict['softkey'] = 'ec2b5b2a576840619bc885a47a025ef6'
   paramDict['imageurl'] = image_url
   result = client.http_request('http://api.ruokuai.com/create.xml', paramDict)
  elif cmp(act, 'report') == 0:
   paramDict['username'] = raw_input('username:')
   paramDict['password'] = raw_input('password:')
   paramDict['id'] = raw_input('id:')
   result = client.http_request('http://api.ruokuai.com/create.xml', paramDict)
  elif cmp(act, 'upload') == 0:
   paramDict['username'] = '********'
   paramDict['password'] = '********'
   paramDict['typeid'] = '2000'
   paramDict['timeout'] = '90'
   paramDict['softid'] = '76693'
   paramDict['softkey'] = 'ec2b5b2a576840619bc885a47a025ef6'
   paramKeys = ['username',
     'password',
     'typeid',
     'timeout',
     'softid',
     'softkey'
    ]

   from PIL import Image
   imagePath = raw_input('Image Path:')
   img = Image.open(imagePath)
   if img is None:
    print 'get file error!'
    continue
   img.save("upload.gif", format="gif")
   filebytes = open("upload.gif", "rb").read()
   result = client.http_upload_image("http://api.ruokuai.com/create.xml", paramKeys, paramDict, filebytes)
  
  elif cmp(act, 'help') == 0:
   print 'info'
   print 'register'
   print 'recharge'
   print 'url'
   print 'report'
   print 'upload'
   print 'help'
   print 'exit'
  elif cmp(act, 'exit') == 0:
   break
  
  return result

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python数组条件过滤filter函数使用示例
Jul 22 Python
Python基于twisted实现简单的web服务器
Sep 29 Python
Python多线程爬虫简单示例
Mar 04 Python
python爬虫爬取快手视频多线程下载功能
Feb 28 Python
Python实现的银行系统模拟程序完整案例
Apr 12 Python
使用celery执行Django串行异步任务的方法步骤
Jun 06 Python
Python进度条的制作代码实例
Aug 31 Python
Python实现剪刀石头布小游戏(与电脑对战)
Dec 31 Python
django Layui界面点击弹出对话框并请求逻辑生成分页的动态表格实例
May 12 Python
python+selenium实现12306模拟登录的步骤
Jan 21 Python
基于tensorflow __init__、build 和call的使用小结
Feb 26 Python
如何使用PyCharm及常用配置详解
Jun 03 Python
Python Django 页面上展示固定的页码数实现代码
Aug 21 #Python
详解Python利用random生成一个列表内的随机数
Aug 21 #Python
Python Django 封装分页成通用的模块详解
Aug 21 #Python
Django之编辑时根据条件跳转回原页面的方法
Aug 21 #Python
python numpy 常用随机数的产生方法的实现
Aug 21 #Python
在django模板中实现超链接配置
Aug 21 #Python
python爬虫 批量下载zabbix文档代码实例
Aug 21 #Python
You might like
php 读取文件乱码问题
2010/02/20 PHP
laravel 5 实现模板主题功能
2015/03/02 PHP
ThinkPHP开发--使用七牛云储存
2017/09/14 PHP
PHP实现图片防盗链破解操作示例【解决图片防盗链问题/反向代理】
2020/05/29 PHP
jquery 图片轮换效果
2010/07/29 Javascript
DLL+ ActiveX控件+WEB页面调用例子
2010/08/07 Javascript
Javascript类定义语法,私有成员、受保护成员、静态成员等介绍
2011/12/08 Javascript
js获取通过ajax返回的map型的JSONArray的方法
2014/01/09 Javascript
Jquery简单实现GridView行高亮的方法
2015/06/15 Javascript
Bootstrap源码解读模态弹出框(11)
2016/12/28 Javascript
JS实现标签页切换效果
2017/05/04 Javascript
jQuery手风琴的简单制作
2017/05/12 jQuery
在一般处理程序(ashx)中弹出js提示语
2017/08/16 Javascript
angular4实现tab栏切换的方法示例
2017/10/21 Javascript
vue 自动化路由实现代码
2019/09/03 Javascript
js实现九宫格抽奖
2020/03/19 Javascript
python sqlobject(mysql)中文乱码解决方法
2008/11/14 Python
详解python3百度指数抓取实例
2016/12/12 Python
Python 内置函数memoryview(obj)的具体用法
2017/11/23 Python
使用anaconda的pip安装第三方python包的操作步骤
2018/06/11 Python
从0开始的Python学习016异常
2019/04/08 Python
python -v 报错问题的解决方法
2020/09/15 Python
pymongo insert_many 批量插入的实例
2020/12/05 Python
python 进制转换 int、bin、oct、hex的原理
2021/01/13 Python
使用Html5 Stream开发实时监控系统
2020/06/02 HTML / CSS
澳大利亚足球鞋和服装购物网站:Ultra Football
2018/10/11 全球购物
泰国王权免税店官方网站:KingPower
2019/03/11 全球购物
c语言常见笔试题总结
2016/09/05 面试题
DELPHI中如何调用API,可举例说明
2014/01/16 面试题
本科生个人求职自荐信
2013/09/26 职场文书
企事业单位求职者的自我评价
2013/12/28 职场文书
环保专业大学生职业规划设计
2014/01/10 职场文书
会计毕业自我鉴定
2014/02/05 职场文书
服装设计师求职信
2014/06/04 职场文书
实习报告范文
2019/07/30 职场文书
Python基础之赋值,浅拷贝,深拷贝的区别
2021/04/30 Python