python實(shí)現(xiàn)帶驗(yàn)證碼網(wǎng)站的自動(dòng)登陸實(shí)現(xiàn)代碼
早聽說(shuō)用python做網(wǎng)絡(luò)爬蟲非常方便,正好這幾天單位也有這樣的需求,需要登陸XX網(wǎng)站下載部分文檔,于是自己親身試驗(yàn)了一番,效果還不錯(cuò)。
本例所登錄的某網(wǎng)站需要提供用戶名,密碼和驗(yàn)證碼,在此使用了python的urllib2直接登錄網(wǎng)站并處理網(wǎng)站的Cookie。
Cookie的工作原理:
Cookie由服務(wù)端生成,然后發(fā)送給瀏覽器,瀏覽器會(huì)將Cookie保存在某個(gè)目錄下的文本文件中。在下次請(qǐng)求同一網(wǎng)站時(shí),會(huì)發(fā)送該Cookie給服務(wù)器,這樣服務(wù)器就知道該用戶是否合法以及是否需要重新登錄。
Python提供了基本的cookielib庫(kù),在首次訪問(wèn)某頁(yè)面時(shí),cookie便會(huì)自動(dòng)保存下來(lái),之后訪問(wèn)其它頁(yè)面便都會(huì)帶有正常登錄的Cookie了。
原理:
(1)激活cookie功能
(2)反“反盜鏈”,偽裝成瀏覽器訪問(wèn)
(3)訪問(wèn)驗(yàn)證碼鏈接,并將驗(yàn)證碼圖片下載到本地
(4)驗(yàn)證碼的識(shí)別方案網(wǎng)上較多,python也有自己的圖像處理庫(kù),此例調(diào)用了火車頭采集器的OCR識(shí)別接口。
(5)表單的處理,可用fiddler等抓包工具獲取需要提交的參數(shù)
(6)生成需要提交的數(shù)據(jù),生成http請(qǐng)求并發(fā)送
(7)根據(jù)返回的js頁(yè)面判斷是否登陸成功
(8)登陸成功后下載其它頁(yè)面
此例中使用多個(gè)賬號(hào)輪詢登陸,每個(gè)賬號(hào)下載3個(gè)頁(yè)面。
下載網(wǎng)址因?yàn)槟承﹩?wèn)題,就不透露了。
以下是部分代碼:
#!usr/bin/env python #-*- coding: utf-8 -*- import os import urllib2 import urllib import cookielib import xml.etree.ElementTree as ET #----------------------------------------------------------------------------- # Login in www.***.com.cn def ChinaBiddingLogin(url, username, password): # Enable cookie support for urllib2 cookiejar=cookielib.CookieJar() urlopener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) urllib2.install_opener(urlopener) urlopener.addheaders.append(('Referer', 'http://www.chinabidding.com.cn/zbw/login/login.jsp')) urlopener.addheaders.append(('Accept-Language', 'zh-CN')) urlopener.addheaders.append(('Host', 'www.chinabidding.com.cn')) urlopener.addheaders.append(('User-Agent', 'Mozilla/5.0 (compatible; MISE 9.0; Windows NT 6.1); Trident/5.0')) urlopener.addheaders.append(('Connection', 'Keep-Alive')) print 'XXX Login......' imgurl=r'http://www.*****.com.cn/zbw/login/image.jsp' DownloadFile(imgurl, urlopener) authcode=raw_input('Please enter the authcode:') #authcode=VerifyingCodeRecognization(r"http://192.168.0.106/images/code.jpg") # Send login/password to the site and get the session cookie values={'login_id':username, 'opl':'op_login', 'login_passwd':password, 'login_check':authcode} urlcontent=urlopener.open(urllib2.Request(url, urllib.urlencode(values))) page=urlcontent.read(500000) # Make sure we are logged in, check the returned page content if page.find('login.jsp')!=-1: print 'Login failed with username=%s, password=%s and authcode=%s' \ % (username, password, authcode) return False else: print 'Login succeeded!' return True #----------------------------------------------------------------------------- # Download from fileUrl then save to fileToSave # Note: the fileUrl must be a valid file def DownloadFile(fileUrl, urlopener): isDownOk=False try: if fileUrl: outfile=open(r'/var/www/images/code.jpg', 'w') outfile.write(urlopener.open(urllib2.Request(fileUrl)).read()) outfile.close() isDownOK=True else: print 'ERROR: fileUrl is NULL!' except: isDownOK=False return isDownOK #------------------------------------------------------------------------------ # Verifying code recoginization def VerifyingCodeRecognization(imgurl): url=r'http://192.168.0.119:800/api?' user='admin' pwd='admin' model='ocr' ocrfile='cbi' values={'user':user, 'pwd':pwd, 'model':model, 'ocrfile':ocrfile, 'imgurl':imgurl} data=urllib.urlencode(values) try: url+=data urlcontent=urllib2.urlopen(url) except IOError: print '***ERROR: invalid URL (%s)' % url page=urlcontent.read(500000) # Parse the xml data and get the verifying code root=ET.fromstring(page) node_find=root.find('AddField') authcode=node_find.attrib['data'] return authcode #------------------------------------------------------------------------------ # Read users from configure file def ReadUsersFromFile(filename): users={} for eachLine in open(filename, 'r'): info=[w for w in eachLine.strip().split()] if len(info)==2: users[info[0]]=info[1] return users #------------------------------------------------------------------------------ def main(): login_page=r'http://www.***.com.cnlogin/login.jsp' download_page=r'http://www.***.com.cn***/***?record_id=' start_id=8593330 end_id=8595000 now_id=start_id Users=ReadUsersFromFile('users.conf') while True: for key in Users: if ChinaBiddingLogin(login_page, key, Users[key]): for i in range(3): pageUrl=download_page+'%d' % now_id urlcontent=urllib2.urlopen(pageUrl) filepath='./download/%s.html' % now_id f=open(filepath, 'w') f.write(urlcontent.read(500000)) f.close() now_id+=1 else: continue #------------------------------------------------------------------------------ if __name__=='__main__': main()
- python selenium循環(huán)登陸網(wǎng)站的實(shí)現(xiàn)
- 如何使用python爬蟲爬取要登陸的網(wǎng)站
- python登陸asp網(wǎng)站頁(yè)面的實(shí)現(xiàn)代碼
- Python3+Appium安裝及Appium模擬微信登錄方法詳解
- python+selenium實(shí)現(xiàn)12306模擬登錄的步驟
- python 模擬登錄B站的示例代碼
- Python模擬鍵盤輸入自動(dòng)登錄TGP
- python中requests模擬登錄的三種方式(攜帶cookie/session進(jìn)行請(qǐng)求網(wǎng)站)
- Python模擬登錄requests.Session應(yīng)用詳解
- Python模擬登錄之滑塊驗(yàn)證碼的破解(實(shí)例代碼)
- python模擬登陸網(wǎng)站的示例
相關(guān)文章
python框架django中結(jié)合vue進(jìn)行前后端分離
本篇將基于Python+Django結(jié)合Vue.js前端框架,為大家介紹如何基于這三者的技術(shù)棧來(lái)實(shí)現(xiàn)一個(gè)前端后離的Web開發(fā)項(xiàng)目。文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01基于python全局設(shè)置id 自動(dòng)化測(cè)試元素定位過(guò)程解析
這篇文章主要介紹了基于python全局設(shè)置id 自動(dòng)化測(cè)試元素定位過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09基于python實(shí)現(xiàn)ROC曲線繪制廣場(chǎng)解析
這篇文章主要介紹了基于python實(shí)現(xiàn)ROC曲線繪制廣場(chǎng)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06http通過(guò)StreamingHttpResponse完成連續(xù)的數(shù)據(jù)傳輸長(zhǎng)鏈接方式
這篇文章主要介紹了http通過(guò)StreamingHttpResponse完成連續(xù)的數(shù)據(jù)傳輸長(zhǎng)鏈接方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02使用pandas實(shí)現(xiàn)csv/excel sheet互相轉(zhuǎn)換的方法
今天小編就為大家分享一篇使用pandas實(shí)現(xiàn)csv/excel sheet互相轉(zhuǎn)換的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12關(guān)于python的縮進(jìn)規(guī)則的知識(shí)點(diǎn)詳解
在本篇文章里小編給大家整理了關(guān)于python的縮進(jìn)規(guī)則的知識(shí)點(diǎn)詳解,有興趣的朋友們可以學(xué)習(xí)下。2020-06-06