滑动验证码-移动滑块
思路:
- 获取滑块
- 建立动作
- 根据滑动的速度滑动
from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver from selenium.webdriver.common.by import By from fake_useragent import UserAgent import requests from time import sleep headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'} import cv2 def get_long(): # 导入图片 img1 = cv2.imread('./imgs/cpt1.png') img2 = cv2.imread('./imgs/cpt2.png') # 边缘化图片 canny1 = cv2.Canny(img1,300,800) canny2 = cv2.Canny(img2,250,500) # 保存图片 cv2.imwrite('./imgs/tcpt1.png',canny1) cv2.imwrite('./imgs/tcpt2.png',canny2) # 加载要匹配的图片 big = cv2.imread('./imgs/tcpt1.png') small = cv2.imread('./imgs/tcpt2.png') # 匹配图片 rs = cv2.matchTemplate(big,small,cv2.TM_CCORR_NORMED) # 显示结果统计 min_val,max_val,min_loc,max_loc = cv2.minMaxLoc(rs) return max_loc[0]/big.shape[1]*340 def get_track(distance): track = [] # 从什么地方开始滑动 current = 0 # 减速的阈值 mid = distance*4/5 # 时间 t = 0.2 # 速度 v = 0 while current < distance: if current <mid: a = 2 else: a = -3 v0 = v v = v0 + a*t move = v0*t + 1/2*a*t*t track.append(round(move))#加入移动轨迹 current += move #记录当前位置 track.append(distance - sum(track)) return track,sum(track) def get_img(): # 创建驱动服务: s = Service('./chromedriver.exe') # 创建chrome浏览器 driver = webdriver.Chrome(service = s) # 访问指定网站 driver.get('https://www.ssssssssss.com/chn/sc/waybill/waybill-detail/xxxxxx') # 设置全局等待对象 wait = WebDriverWait(driver,100) # 设置等待iframe加载完成 wait.until(EC.presence_of_all_elements_located((By.XPATH,"//iframe[@id='tcaptcha_iframe']"))) # 切换到frame driver.switch_to.frame("tcaptcha_iframe") sleep(3) # 获取图片src wait.until(EC.presence_of_all_elements_located((By.XPATH,"//div[@id='slideBgWrap']/img"))) img = driver.find_element(By.XPATH,"//div[@id='slideBgWrap']/img") img_src = img.get_attribute('src') img_src = img_src[:img_src.rfind('&')-1] print(img_src) # 保存图片 save_image(f'{img_src}1','cpt1.png') save_image(f'{img_src}2','cpt2.png') # 滑动验证, # 获取滑动的距离 distance = get_long() # 获取滑动的轨迹 track,long = get_track(distance) # 操作selenium滑动滑块 # 点击滑块 button = driver.find_element(By.XPATH,"//div[@id='tcaptcha_drag_thumb']") webdriver.ActionChains(driver).click_and_hold(button).perform() # 进行拖拽 for t in track: # 开始拖拽 webdriver.ActionChains(driver).move_by_offset(xoffset=t,yoffset=0).perform() # 释放拖拽 webdriver.ActionChains(driver).release().perform() driver.close() def save_image(url,file_name): resp = requests.get(url,headers=headers) with open(f'./imgs/{file_name}','wb') as f: f.write(resp.content) if __name__ == '__main__': get_img()