普通滑動驗證
以http://admin.emaotai.cn/login.aspx為例這類驗證碼只需要我們將滑塊拖動指定位置,處理起來比較簡單。拖動之前需要先將滾動條滾動到指定元素位置。
import time from selenium import webdriver from selenium.webdriver import ActionChains # 新建selenium瀏覽器對象,后面是geckodriver.exe下載后本地路徑 browser = webdriver.Firefox() # 網站登陸頁面 url = 'http://admin.emaotai.cn/login.aspx' # 瀏覽器訪問登錄頁面 browser.get(url) browser.maximize_window() browser.implicitly_wait(5) draggable = browser.find_element_by_id('nc_1_n1z') # 滾動指定元素位置 browser.execute_script("arguments[0].scrollIntoView();", draggable) time.sleep(2) ActionChains(browser).click_and_hold(draggable).perform() # 拖動 ActionChains(browser).move_by_offset(xoffset=247, yoffset=0).perform() ActionChains(browser).release().perform()
拼圖滑動驗證
我們以歐模網很多網站使用的都是類似的方式。因為驗證碼及拼圖都有明顯明亮的邊界,圖片辨識度比較高。所以我們嘗試先用cv2的邊緣檢測識別出邊界,然后進行模糊匹配,匹配出拼圖在驗證碼圖片的位置。
邊緣檢測
pip install opencv-python
cv2模塊提供了多種邊緣檢測算子,包括Sobel、Scharr、Laplacian、prewitt、Canny或Marr—Hildreth等,每種算子得出的結果不同。這里我們用Canny算子,測試了很多算子,這種效果最好。
Canny
我們通過一個程序調整一下canny算子的閾值,使得輸出圖片只包含拼圖輪廓。
import cv2 lowThreshold = 0 maxThreshold = 100 # 最小閾值范圍 0 ~ 500 # 最大閾值范圍 100 ~ 1000 def canny_low_threshold(intial): blur = cv2.GaussianBlur(img, (3, 3), 0) canny = cv2.Canny(blur, intial, maxThreshold) cv2.imshow('canny', canny) def canny_max_threshold(intial): blur = cv2.GaussianBlur(img, (3, 3), 0) canny = cv2.Canny(blur, lowThreshold, intial) cv2.imshow('canny', canny) # 參數0以灰度方式讀取 img = cv2.imread('vcode.png', 0) cv2.namedWindow('canny', cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) cv2.createTrackbar('Min threshold', 'canny', lowThreshold, max_lowThreshold, canny_low_threshold) cv2.createTrackbar('Max threshold', 'canny', maxThreshold, max_maxThreshold, canny_max_threshold) canny_low_threshold(0) # esc鍵退出 if cv2.waitKey(0) == 27: cv2.destroyAllWindows()
測試了若干個圖片發現最小閾值100、最大閾值500輸出結果比較理想。
拼圖匹配
我們用cv2的matchTemplate方法進行模糊匹配,匹配方法用CV_TM_CCOEFF_NORMED歸一化相關系數匹配。
幾種方法算法詳見。
【1】 平方差匹配 method=CV_TM_SQDIFF square dirrerence(error)
這類方法利用平方差來進行匹配,最好匹配為0.匹配越差,匹配值越大.
【2】標准平方差匹配 method=CV_TM_SQDIFF_NORMED standard square dirrerence(error)
【3】 相關匹配 method=CV_TM_CCORR
這類方法采用模板和圖像間的乘法操作,所以較大的數表示匹配程度較高,0標識最壞的匹配效果.
【4】 標准相關匹配 method=CV_TM_CCORR_NORMED
【5】 相關匹配 method=CV_TM_CCOEFF
這類方法將模版對其均值的相對值與圖像對其均值的相關值進行匹配,1表示完美匹配,
-1表示糟糕的匹配,0表示沒有任何相關性(隨機序列).
【6】標准相關匹配 method=CV_TM_CCOEFF_NORMED
canndy_test.py:
import cv2 import numpy as np def matchImg(imgPath1,imgPath2): imgs = [] # 原始圖像,用於展示 sou_img1 = cv2.imread(imgPath1) sou_img2 = cv2.imread(imgPath2) # 原始圖像,灰度 # 最小閾值100,最大閾值500 img1 = cv2.imread(imgPath1, 0) blur1 = cv2.GaussianBlur(img1, (3, 3), 0) canny1 = cv2.Canny(blur1, 100, 500) cv2.imwrite('temp1.png', canny1) img2 = cv2.imread(imgPath2, 0) blur2 = cv2.GaussianBlur(img2, (3, 3), 0) canny2 = cv2.Canny(blur2, 100, 500) cv2.imwrite('temp2.png', canny2) target = cv2.imread('temp1.png') template = cv2.imread('temp2.png') # 調整顯示大小 target_temp = cv2.resize(sou_img1, (350, 200)) target_temp = cv2.copyMakeBorder(target_temp, 5, 5, 5, 5, cv2.BORDER_CONSTANT, value=[255, 255, 255]) template_temp = cv2.resize(sou_img2, (200, 200)) template_temp = cv2.copyMakeBorder(template_temp, 5, 5, 5, 5, cv2.BORDER_CONSTANT, value=[255, 255, 255]) imgs.append(target_temp) imgs.append(template_temp) theight, twidth = template.shape[:2] # 匹配拼圖 result = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED) # 歸一化 cv2.normalize( result, result, 0, 1, cv2.NORM_MINMAX, -1 ) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
#如果不需要看后面的效果,只要返回位置,把下面的注釋去掉
#return max_loc[0]
# 匹配后結果畫圈 cv2.rectangle(target,max_loc,(max_loc[0]+twidth,max_loc[1]+theight),(0,0,255),2) target_temp_n = cv2.resize(target, (350, 200)) target_temp_n = cv2.copyMakeBorder(target_temp_n, 5, 5, 5, 5, cv2.BORDER_CONSTANT, value=[255, 255, 255]) imgs.append(target_temp_n) imstack = np.hstack(imgs) cv2.imshow('stack'+str(max_loc), imstack) cv2.waitKey(0) cv2.destroyAllWindows() matchImg('vcode_data/out_'+str(1)+'.png','vcode_data/in_'+str(1)+'.png')
我們測試幾組數據,發現准確率拿來玩玩尚可。max_loc就是匹配出來的位置信息,我們只需要按照位置進行拖動即可。
完整程序
完整流程1.實例化瀏覽器 2.點擊登陸,彈出滑動驗證框 3.分別新建標簽頁打開背景圖及拼圖 4.全屏截圖后按照尺寸裁剪 5.模糊匹配兩張圖片,獲取匹配結果位置信息 6.將位置信息轉為頁面上的位移距離 7.拖動滑塊到指定位置
import time import cv2 import canndy_test from selenium import webdriver from selenium.webdriver import ActionChains # 新建selenium瀏覽器對象,后面是geckodriver.exe下載后本地路徑 browser = webdriver.Firefox() # 網站登陸頁面 url = 'https://www.om.cn/login' # 瀏覽器訪問登錄頁面 browser.get(url) handle = browser.current_window_handle # 等待3s用於加載腳本文件 browser.implicitly_wait(3) # 點擊登陸按鈕,彈出滑動驗證碼 btn = browser.find_element_by_class_name('login_btn1') btn.click() # 獲取iframe元素,切到iframe frame = browser.find_element_by_id('tcaptcha_iframe') browser.switch_to.frame(frame) time.sleep(1) # 獲取背景圖src targetUrl = browser.find_element_by_id('slideBg').get_attribute('src') # 獲取拼圖src tempUrl = browser.find_element_by_id('slideBlock').get_attribute('src') # 新建標簽頁 browser.execute_script("window.open('');") # 切換到新標簽頁 browser.switch_to.window(browser.window_handles[1]) # 訪問背景圖src browser.get(targetUrl) time.sleep(3) # 截圖 browser.save_screenshot('temp_target.png') w = 680 h = 390 img = cv2.imread('temp_target.png') size = img.shape top = int((size[0] - h) / 2) height = int(h + ((size[0] - h) / 2)) left = int((size[1] - w) / 2) width = int(w + ((size[1] - w) / 2)) cropped = img[top:height, left:width] # 裁剪尺寸 cv2.imwrite('temp_target_crop.png', cropped) # 新建標簽頁 browser.execute_script("window.open('');") browser.switch_to.window(browser.window_handles[2]) browser.get(tempUrl) time.sleep(3) browser.save_screenshot('temp_temp.png') w = 136 h = 136 img = cv2.imread('temp_temp.png') size = img.shape top = int((size[0] - h) / 2) height = int(h + ((size[0] - h) / 2)) left = int((size[1] - w) / 2) width = int(w + ((size[1] - w) / 2)) cropped = img[top:height, left:width] cv2.imwrite('temp_temp_crop.png', cropped) browser.switch_to.window(handle) # 模糊匹配兩張圖片 move = canndy_test.matchImg('temp_target_crop.png', 'temp_temp_crop.png') # 計算出拖動距離 distance = int(move / 2 - 27.5) + 2 draggable = browser.find_element_by_id('tcaptcha_drag_thumb') ActionChains(browser).click_and_hold(draggable).perform() # 拖動 ActionChains(browser).move_by_offset(xoffset=distance, yoffset=0).perform() ActionChains(browser).release().perform() time.sleep(10)
tips:可能會存在第一次不成功的情況,雖然拖動到了指定位置但是提示網絡有問題、拼圖丟失。可以進行循環迭代直到拼成功為止。通過判斷iframe中id為slideBg的元素是否存在,如果成功了則不存在,失敗了會刷新拼圖讓你重新拖動。
if(isEleExist(browser,'slideBg')): # retry else: return def isEleExist(browser,id): try: browser.find_element_by_id(id) return True except: return False