python爬蟲豆瓣網(wǎng)的模擬登錄實(shí)現(xiàn)-創(chuàng)新互聯(lián)

本篇文章為大家展示了python爬蟲豆瓣網(wǎng)的模擬登錄實(shí)現(xiàn),內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

成都創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比站前網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式站前網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋站前地區(qū)。費(fèi)用合理售后完善,十年實(shí)體公司更值得信賴。

一、想要實(shí)現(xiàn)登錄豆瓣關(guān)鍵點(diǎn)

分析真實(shí)post地址 ----尋找它的formdata,如下圖,按瀏覽器的F12可以找到。

python爬蟲豆瓣網(wǎng)的模擬登錄實(shí)現(xiàn)

實(shí)戰(zhàn)操作

  • 實(shí)現(xiàn):模擬登錄豆瓣,驗(yàn)證碼處理,登錄到個(gè)人主頁(yè)就算是success

  • 數(shù)據(jù):沒(méi)有抓取數(shù)據(jù),此實(shí)戰(zhàn)主要是模擬登錄和處理驗(yàn)證碼的學(xué)習(xí)。要是有需求要抓取數(shù)據(jù),編寫相關(guān)的抓取規(guī)則即可抓取內(nèi)容。

登錄成功展示如圖:

python爬蟲豆瓣網(wǎng)的模擬登錄實(shí)現(xiàn)

spiders文件夾中DouBan.py主要代碼如下:

# -*- coding: utf-8 -*-
import scrapy,urllib,re
from scrapy.http import Request,FormRequest
import ruokuai
'''
遇到不懂的問(wèn)題?Python學(xué)習(xí)交流群:821460695滿足你的需求,資料都已經(jīng)上傳群文件,可以自行下載!
'''
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)]#可以傳遞一個(gè)標(biāo)示符來(lái)使用多個(gè)。如meta={'cookiejar': 1}這句,后面那個(gè)1就是標(biāo)示符

 def parse(self, response):
  captcha=response.xpath('//*[@id="captcha_image"]/@src').extract() #獲取驗(yàn)證碼圖片的鏈接
  print captcha
  if len(captcha)>0:
   '''此時(shí)有驗(yàn)證碼'''
   #人工輸入驗(yàn)證碼
   #urllib.urlretrieve(captcha[0],filename="C:/Users/pujinxiao/Desktop/learn/douban20170405/douban/douban/spiders/captcha.png")
   #captcha_value=raw_input('查看captcha.png,有驗(yàn)證碼請(qǐng)輸入:')

   #用快若打碼平臺(tái)處理驗(yàn)證碼--------驗(yàn)證碼是任意長(zhǎng)度字母,成功率較低
   captcha_value=ruokuai.get_captcha(captcha[0])
   reg=r'<Result>(.*?)</Result>'
   reg=re.compile(reg)
   captcha_value=re.findall(reg,captcha_value)[0]
   print '驗(yàn)證碼為:',captcha_value

   data={
    "form_email": "weisuen007@163.com",
    "form_password": "weijc7789",
    "captcha-solution": captcha_value,
    #"redir": "https://www.douban.com/people/151968962/",  #設(shè)置需要轉(zhuǎn)向的網(wǎng)址,由于我們需要爬取個(gè)人中心頁(yè),所以轉(zhuǎn)向個(gè)人中心頁(yè)
   }
  else:
   '''此時(shí)沒(méi)有驗(yàn)證碼'''
   print '無(wú)驗(yàn)證碼'
   data={
    "form_email": "weisuen007@163.com",
    "form_password": "weijc7789",
    #"redir": "https://www.douban.com/people/151968962/",
   }
  print '正在登陸中......'
  ####FormRequest.from_response()進(jìn)行登陸
  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 '登錄失敗,請(qǐng)重試!'
  else:
   print '登錄成功'
   '''
   可以繼續(xù)后續(xù)的爬取工作
   '''

ruokaui.py代碼如下:

我所用的是若塊打碼平臺(tái),選擇url識(shí)別驗(yàn)證碼,直接給打碼平臺(tái)驗(yàn)證碼圖片的鏈接地址,傳回驗(yàn)證碼的值。

# -*- coding: utf-8 -*-
import sys, hashlib, os, random, urllib, urllib2
from datetime import *
'''
遇到不懂的問(wèn)題?Python學(xué)習(xí)交流群:821460695滿足你的需求,資料都已經(jīng)上傳群文件,可以自行下載!
'''
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('請(qǐng)輸入打碼方式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

上述內(nèi)容就是python爬蟲豆瓣網(wǎng)的模擬登錄實(shí)現(xiàn),你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計(jì)公司行業(yè)資訊頻道。

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。

網(wǎng)頁(yè)題目:python爬蟲豆瓣網(wǎng)的模擬登錄實(shí)現(xiàn)-創(chuàng)新互聯(lián)
文章源于:http://muchs.cn/article48/coeehp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁(yè)設(shè)計(jì)公司、網(wǎng)站設(shè)計(jì)、網(wǎng)站設(shè)計(jì)公司品牌網(wǎng)站制作、面包屑導(dǎo)航、營(yíng)銷型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

小程序開發(fā)