selenium + opencv突破滑动验证
前事准备
1. 需要使用的模块requests,numpy,selenium,cv2,time
2. 需要浏览器驱动 chromedriver.exe
3. 安装opencv模块(版本不要过新)
""" 我这里使用的版本
pip uninstall opencv-python # 卸载
pip install opencv-python==3.4.2.16 # 安装
pip install opencv-contrib-python==3.4.2.16
"""
实现代码
# 注意使用的是selenium 运行时要考虑网路延时
import requests
import cv2 as cv
from time import sleep
import numpy as np
from selenium import webdriver
from selenium.webdriver import ActionChains
# 导入浏览器驱动
web = webdriver.Chrome(r'chromedriver.exe')
# 访问指定页面
web.get('https://dun.163.com/trial/sense')
sleep(2) # 防止网路延迟数据加载不成
# 找到滑动选项
web.find_element_by_xpath('//li[@captcha-type="jigsaw"]').click()
sleep(2)
# 找到滑动的图片
web.find_element_by_xpath('//div[@class="yidun_intellisense yidun_intellisense--light"]/div/div').click()
sleep(2)
# 获取 背景图与滑动块图片的连接
background_image_url = web.find_element_by_xpath('//div[@class="yidun_bgimg"]/img[1]').get_attribute('src')
slider_image_url = web.find_element_by_xpath('//div[@class="yidun_bgimg"]/img[2]').get_attribute('src')
# 获取两张图片 并保存
background_image = requests.get(background_image_url).content
slider_image = requests.get(slider_image_url).content
background_image_path = 'background_image' + '.jpg'
with open(background_image_path, mode='wb') as f:
f.write(background_image)
slider_image_path = 'slider_image' + '.jpg'
with open(slider_image_path, mode='wb') as f:
f.write(slider_image)
sleep(1)
# 读取图片
background = cv.imread(background_image_path)
slider = cv.imread(slider_image_path)
# 灰度处理图片 图片只有白黑
background = cv.cvtColor(background, cv.COLOR_BGR2GRAY)
slider = cv.cvtColor(slider, cv.COLOR_BGR2GRAY)
# 去除白色部分 获取滑块正常大小
slider = slider[slider.any(1)]
# 进行相似度匹配返回坐标数组
result = cv.matchTemplate(background, slider, cv.TM_CCOEFF_NORMED)
# 获取相似度最高像素坐标 x 是像素高度 y 是像素距离
x, y = np.unravel_index(result.argmax(), result.shape)
# 等比例缩放问题 (滑动距离) 300比320 但是起始位置与背景图位置有偏差,不做等比例可以通过识别
# distance = int(y*0.9375) - 2 # 等比例缩放 0.9375
sleep(1)
# 使用动作链
btn = web.find_element_by_xpath('//div[@class="yidun_control"]/div[2]')
ActionChains(web).drag_and_drop_by_offset(btn,xoffset=y,yoffset=0).perform()
sleep(2)
web.close()
实现效果