selenium实例:自动刷青马网课实现登陆 python实现自动登陆 利用pytesseract自动识别验证码并登录
準(zhǔn)備工作
首先得先安裝好python,IDE,selenium,Firefox瀏覽器
這里可以供參考
Windows下的python的安裝全步驟,分圖詳解
Windows+Firefox(Chrome)+selenium+python配置并更改源(加快下載速度,不然很慢)
安裝相關(guān)的庫
pip install 相關(guān)庫的名稱即可
一般來說,需要檢查time,pytesseract,PIL等庫是否被正確安裝
如果出現(xiàn)報錯,安裝上相應(yīng)的庫即可
推薦使用anconda進(jìn)行
不用也可,測試環(huán)境在安裝好selenium的anconda下進(jìn)行
注意,原本的anconda并沒有包括selenium庫,需要自行安裝
另外,我們還需要Tesseract-OCR這個軟件,用于ocr識別相關(guān)驗證碼
關(guān)于這個軟件的信息請自行百度
總的來說,為了運(yùn)行這個實(shí)例,你需要:
1.一臺裝有Windows的電腦和網(wǎng)絡(luò)
2.python3及其IDE(如pycharm,vscode等),最好是anconda
3.相關(guān)的python庫,如PIL,selenium等
4.運(yùn)行ocr所需要的軟件Tesseract-OCR
5.Firefox瀏覽器及其對應(yīng)webdriver
相關(guān)功能的實(shí)現(xiàn)
import pytest import time import json import pytesseract import re import requests import pyautoguifrom time import sleep from PIL import Image,ImageEnhance,ImageOps from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver import FirefoxOptions from selenium.webdriver.firefox.firefox_binary import FirefoxBinaryclass Class:#該函數(shù)功能是初始化def __init__(self,un,pw,cbe,cen):opts = FirefoxOptions()# opts.add_argument("--headless")option_profile = webdriver.FirefoxProfile()option_profile.set_preference("plugin.state.flash",2)option_profile.set_preference("security.insecure_field_warning.contextual.enabled",False)#上面的部分是對瀏覽器的設(shè)置,使flash能自動播放self.driver = webdriver.Firefox(firefox_profile=option_profile,options=opts)self.driver.get('http://hnqmgc.17el.cn/')self.driver.set_window_size(1920,1080)#創(chuàng)建一個瀏覽器對象并打開網(wǎng)站,設(shè)置窗口尺寸為1920*1080self.un=unself.pw=pwself.cbe=cbeself.cen=cen#接收傳入的un用戶名,pw密碼,cbe課程開始刷的id,cen課程結(jié)束刷的idprint('初始化瀏覽器成功')#該函數(shù)功能是處理驗證碼def processing_pictures(self):sleep(1)self.driver.find_element(By.ID, "code").click()sleep(1)#找到驗證碼,點(diǎn)一下刷新驗證碼。因為這個函數(shù)在一個循環(huán)體,一次可能不能登錄成功。self.driver.save_screenshot('pictures.png')#保存網(wǎng)頁截圖left=1365top=319right=1365+48bottom=319+18#上面的是驗證碼的坐標(biāo)imge=Image.open("pictures.png").crop((left, top, right, bottom))#imge.show() 作用是運(yùn)行時檢查錯誤用的,把處理后的圖像輸出img = imge.convert("L")#圖片轉(zhuǎn)灰度,由于這個驗證碼太腦殘,不需要進(jìn)行插值等特殊處理pixdata = img.load()w, h = img.sizethreshold = 160# img.show()for y in range(h):for x in range(w):if pixdata[x, y] < threshold:pixdata[x, y] = 255else:pixdata[x, y] = 0#取反色#img.show()pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"#這里應(yīng)該是你的ocr程序的安裝地址result = pytesseract.image_to_string(img)#將圖片轉(zhuǎn)換為字符串resultj = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", result)#正則表達(dá)式,除去特殊字符result_four = resultj[0:4]print('驗證碼是'+str(result_four))return result_four#該函數(shù)功能是登錄def login(self):print('正在登錄中,請稍后')n=0#下面這是一個循環(huán),因為驗證碼可能不能一次正確,需要不斷嘗試while True:n+=1print('第%d次登錄中'%n)#下面這兩個sleep表示暫停1秒,因為網(wǎng)頁需要加載,這樣更保險sleep(1)self.driver.refresh()#刷新頁面,因為上一次循環(huán)登錄過,刷新重來sleep(1)self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")#該js腳本作用是將滾動條滑至頂部self.driver.find_element(By.ID, "login_btn").click()self.driver.find_element(By.ID, "UserName").send_keys(self.un)self.driver.find_element(By.ID, "Password").send_keys(self.pw)#輸入用戶名以及密碼code=self.processing_pictures()self.driver.find_element(By.ID, "codein").send_keys(code)self.driver.find_element(By.ID, "sub").click()try:alert=self.driver.switch_to_alert()alert.accept()except:break#如果沒有彈出警告窗,也就是登錄成功,循環(huán)體結(jié)束,如果彈出,則accept關(guān)閉彈窗'''其實(shí)這個被注釋的腳本也可以實(shí)現(xiàn)檢查是否正常登錄sleep(1)self.driver.refresh()sleep(1)html = self.driver.page_sourceif html.find('個人中心') == -1:break'''print('第%d次登錄失敗,正在重試'%n)self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")#作用見上面print('登錄成功,一共嘗試了%d次'%n)self.attend_class()#該函數(shù)功能是上網(wǎng)課def attend_class(self):print('開始刷課')for course in range(int(self.cbe),int(self.cen)+1):url='http://hnqmgc.17el.cn/ymzs/zxzr/484770_qmzx.shtml?kcid='+str(course)self.driver.get(url)# 進(jìn)入相關(guān)課程播放頁面#sleep(30) 如果播放插件被阻塞,應(yīng)該預(yù)留一點(diǎn)時間再重新打開它# coursename=self.driver.find_element_by_id("courseName").text()print('當(dāng)前正在刷id為{0}的課程:'.format(course))#下面的部分填坑sleep(5)if __name__ == '__main__':print('****************歡迎使用青馬網(wǎng)課刷課系統(tǒng)v1.0!*****************')print('* Author:STL_CC 2020.03.18 v1.0 *')print('* Blog:https://blog.csdn.net/STL_CC *')print('*************************************************************')print('請輸入相關(guān)信息:')username=input('Username:')password=input('Password:')cb=input('開始課程id:')ce=input('結(jié)束課程id:')print('開始刷課!')a = Class(username,password,cb,ce)a.login()后話
1.以上程序僅實(shí)現(xiàn)了登陸功能,具體的刷課進(jìn)程可見Python刷青馬,但是他這個實(shí)現(xiàn)方法只是模擬鼠標(biāo)點(diǎn)擊,需要圖形化界面,應(yīng)用場景十分有限。
2.聽說JavaScript能控制flash播放器的運(yùn)行,而且selenium可以使用自定義js腳本,然而筆者沒有學(xué)過,而且已經(jīng)開發(fā)了快三天,還要上課,吃不消,待有時間學(xué)完js后可能會在此填坑,如果哪位大佬懂js,可以一起繼續(xù)開發(fā)。
3.課程id就是每個視頻最前面那個東東,你也可以觀察視頻鏈接
4.由于自動化測試工具的特殊性,可能要針對自己的電腦運(yùn)行環(huán)境進(jìn)行一些特殊的處理,這個程序我也鼓搗了很久才調(diào)好環(huán)境,如果由大佬需要技術(shù)支持,可以私信筆者。
5.這里是開發(fā)的套件包,Firefox 55以上不支持flash自動運(yùn)行,這是可以支持的版本,請用此套件開發(fā)
鏈接:https://pan.baidu.com/s/1XXHxkd5KXs5rRFyS19yt6A
提取碼:q3pp
emmmm 附件里的python程序缺少了幾個庫,以上面的為準(zhǔn)
最近更新:筆者已經(jīng)對js控制flash控件進(jìn)行了測試,得要這個控件的屬性對外開放才行,所以目前來看只有兩種解決的方法,一個是使用autoit或者pyautogui等進(jìn)行模擬鼠標(biāo)點(diǎn)擊,另一種是我猜的,可以抓包欺騙服務(wù)器
與其花這幾天時間做這個工程,其實(shí)還不如老老實(shí)實(shí)刷,但是,通過這三天來的不斷測試,筆者掌握python復(fù)雜編程的能力有了很大提高。也了解了網(wǎng)頁的基本結(jié)構(gòu)和selenium工具,以后應(yīng)對簡單的工程,簽個到啥的還是很容易上手了的
也希望這個項目的某些方面能給讀者以啟發(fā)
總結(jié)
以上是生活随笔為你收集整理的selenium实例:自动刷青马网课实现登陆 python实现自动登陆 利用pytesseract自动识别验证码并登录的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php函数scandir_PHP函数gl
- 下一篇: python qq群文件_Python随