python selenium 利用pyautogui+ActionChains 完美解决我的滑块验证登录问题

在解决滑块验证的时候不知道什么原因明明是滑块已经对上了,代码执行就是会校验不通过,手动时就可以,中间也做利用ActionChains模块减速滑动轨迹的操作,但仍然不行,后面在执行代码中添加了pyautogui模块使鼠标悬停在屏幕中的某个点而不改变ActionChains鼠标的定位后终于每次都能通过了
附的代码里没有把减速滑动部分加上,有需要加的可以自动搜索一下

```python
from selenium import webdriver
import pyautogui
import requests
import time
import cv2
import numpy as np
from selenium.webdriver import ActionChains


driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')
driver.get('https://dun.163.com/trial/jigsaw')
time.sleep(5)

# 点击进入滑块界面
driver.find_element_by_xpath('//li[text()="弹出式"]').click()
time.sleep(1)
# 点击完成验证
driver.find_element_by_css_selector('button.tcapt-bind_btn.tcapt-bind_btn--login.j-pop').click()
time.sleep(3)

while True:
    # 获取两张图片
    url_s = driver.find_element_by_class_name('yidun_jigsaw').get_attribute('src')
    url_b = driver.find_element_by_class_name('yidun_bg-img').get_attribute('src')
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.41 Safari/537.36'
    }
    res_s = requests.get(url_s, headers=headers)
    data_s = res_s.content
    res_b = requests.get(url_b, headers=headers)
    data_b = res_b.content
    # 保存图片
    with open('pic_s.png', 'wb')as f:
        f.write(data_s)
    with open('pic_b.png', 'wb')as f:
        f.write(data_b)

    # 使用opencv读取两张图片
    simg = cv2.imread('pic_s.png')
    bimg = cv2.imread('pic_b.png')

    # 灰度处理,降低偏差
    s_img = cv2.cvtColor(simg, cv2.COLOR_BGR2GRAY)
    b_img = cv2.cvtColor(bimg, cv2.COLOR_BGR2GRAY)

    # 保存两张灰度处理的图片
    cv2.imwrite('hui_simg.png', s_img)
    cv2.imwrite('hui_bimg.png', b_img)

    # 处理滑块图片,保存有效部分
    s_img = s_img[s_img.any(1)]

    # opencv的匹配算法,匹配模块寻找两张图片的相似之处
    result = cv2.matchTemplate(b_img, s_img, cv2.TM_CCOEFF_NORMED)
    print('result', result)

    # 获取坐标
    # 获取最大索引
    index_max = np.argmax(result)
    # 获取到坐标
    y, x = np.unravel_index(index_max, result.shape)
    print("y:", y, "x:", x)
    time.sleep(2)
    # 定位到滑块
    ele = driver.find_element_by_xpath(
        '/html/body/main/div[1]/div/div[2]/div[2]/div[1]/div[3]/div/div/div[3]/div[2]/div/div/div[2]/div/div[2]/div[2]')

    # 实例化对象
    action = ActionChains(driver)
    # 拖动滑块
    time.sleep(1)
    action.click_and_hold(ele).perform()
    time.sleep(0.5)
    pyautogui.moveTo(pyautogui.size()[0] / 2, pyautogui.size()[1] / 2)  # 鼠标晃到屏幕中间的位置,不影响后面鼠标的起始位置
    action.move_by_offset(xoffset=x / 480 * 320 + 10, yoffset=0).perform()  # 480是图片保存在本地的宽度,320是网页打开图片显示的宽度
    time.sleep(1)
    action.release().perform()
    # 定位到验证成功
    time.sleep(1)
    try:
        driver.find_element_by_xpath('/html/body/main/div[1]/div/div[2]/div[2]/div[1]/div[3]/div/div/div[3]/div[2]/div/div/div[2]/div/div[2]/div[2]')
    except:
        break

你可能感兴趣的:(1024程序员节,python,selenium)