下面代码可以解决类似图中的滑动验证码,几年前写的,当时是可以用的,现在不清楚,仅供参考 =͟͟͞͞(꒪⌓꒪*)
from PIL import ImageGrab, Image
import time
from pymouse import PyMouse
from pykeyboard import PyKeyboard
import cv2 as cv
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
class ImageMatch:
driver = None
def __init__(self):
self.mouse = PyMouse()
self.keyboard = PyKeyboard()
self.driver = ImageMatch.get_webdriver()
@classmethod
def get_webdriver(cls):
if cls.driver == None:
cls.driver = webdriver.Chrome()
cls.driver.implicitly_wait(3)
cls.driver.maximize_window()
cls.driver.get('http://127/0.0.1#/login')
cls.driver.find_element_by_css_selector(".el-input__inner").send_keys("rjzt")
cls.driver.find_element_by_xpath("//input[@autocomplete='new-password']").send_keys("123456")
cls.driver.find_element_by_css_selector('button').click()
time.sleep(2)
# print(id(cls.driver))
return cls.driver
def find_image(self, filename):
ImageGrab.grab().save('./screen.png')
source = cv.imread('./screen.png') # 打开屏幕截图
templete = cv.imread(filename) # 打开模板图片
# 调用openCV自带的matchTemplate方法进行模板匹配
result = cv.matchTemplate(source, templete, cv.TM_CCOEFF_NORMED)
location = cv.minMaxLoc(result)
pos_start = location[3] # 获取匹配成功后的起始坐标
# print(location) #(-0.5183663964271545, 1.0, (393, 557), (503, 336))
# 计算匹配对象的中心坐标x,y
x = int(pos_start[0]) + int(templete.shape[1] / 2)
y = int(pos_start[1]) + int(templete.shape[0] / 2)
# 根据匹配度返回坐标,如果小于95%,则返回无效坐标(-1,-1)
similarity = location[1]
if similarity >= 0.9:
return (x, y)
else:
return (-1, -1)
# 封装单击操作
def click(self, filename):
x, y = self.find_image(filename)
self.mouse.click(x, y)
print("在位置[%d,%d]处点击" % (x, y))
# 封装输入操作
def input(self, filename, content):
x, y = self.find_image(filename)
self.mouse.click(x, y)
self.keyboard.type_string(content)
print("在位置[%d,%d]处,输入:%s" % (x, y, content))
def move_pic(self):
button = self.driver.find_element_by_css_selector('.range-btn')
time.sleep(1.5)
find = ImageMatch()
find.find_image('./test3.png')
x, y = find.find_image('./test3.png')
print(x, y)
time.sleep(1.5)
action = ActionChains(self.driver)
action.drag_and_drop_by_offset(button, xoffset=x - 820, yoffset=0).perform()
def login(self):
i = 0
while i < 3:
try:
ImageMatch().move_pic()
i += 1
except:
print("登陆成功了.....")
break
def quit(self):
self.driver.quit()
if __name__ == '__main__':
ImageMatch().login()
ImageMatch().quit()