python实现滑动验证

做自动化测试的时候,需要自动登录QQ邮箱,在网上找的都是基于selenium的:参考链接,但是代码在本地运行并没有取得满意的效果:滑动不成功
而且每个滑动解锁的网页不同,编码和格式就不同,复用率太低了!举个例子:

button = browser.find_element_by_id('tcaptcha_drag_button')
x, y = button.location.get('x'), button.location.get('y')
print("location:",x,y)

这段代码是获取滑动解锁按钮坐标的,但是返回的是(33,193),而不是根据桌面像素(1920,1080)应该得到的坐标。
在这里插入图片描述
查看网页源码发现,这个验证框:width:300px,height:230px,因此坐标是根据这个iframe框架得到的,所以后面的拖动按钮并滑动就会出现问题,(比如拖动一点点就会报错:超出(300,230)边界错误),而且总是拖不到右边,搞了好久都不行(部分原因是我前端基础不牢固)
还有一些其他问题我就不再说了,反正就是心态爆炸:不想用selenium搞滑动了!
我就换了一个方法,按钮的图片定位,然后实现滑动验证:图片定位具体可以参考:ac.find_template识别图片并定位

直接上代码吧:

#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import paramiko
import pyautogui
import os
from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from Auto_Test.base_action import match

def login_in():
    browser = webdriver.Firefox()
    browser.maximize_window()
    browser.get("https://mail.qq.com/")
    browser.switch_to.frame("login_frame")
    browser.find_element_by_class_name("inputstyle").clear()
    browser.find_element_by_class_name("inputstyle").send_keys("xxxxx")
    browser.find_element_by_class_name("inputstyle.password").clear()
    browser.find_element_by_class_name("inputstyle.password").send_keys("xxxxx")
    browser.find_element_by_id("login_button").click()
    browser.find_element_by_class_name("login_button").click()
    time.sleep(2)
    browser.switch_to.frame("tcaptcha_iframe")

    time.sleep(3)
    # 等待图片加载出来
    WebDriverWait(browser, 5, 0.5).until(
        EC.presence_of_element_located((By.ID, "tcaptcha_drag_button")))
    # button = browser.find_element_by_id('tcaptcha_drag_button')
    # x, y = button.location.get('x'), button.location.get('y')
    # print("location:",x,y)
    lx,ly=match("QQmail-slick")
    lz=[x for x in range(120,200,3)]
    for i in lz:
        pyautogui.moveTo(lx,ly)
        pyautogui.dragRel(i,0,duration=2,button='left')
        time.sleep(1)
        pyautogui.moveRel(-i,0)

        try:
            alert = browser.find_element_by_id('guideText').text
        except Exception as e:
            print('get alert error: %s' % e)
            alert = ''
        if alert:
            print(u'滑块位移需要调整: %s' % alert)
            sleep(3)
        else:
            print('滑块验证通过')
            browser.switch_to.parent_frame()  # 验证成功后跳回最外层页面
            break

from Auto_Test.base_action import match中的函数如下:

def match(target, show=True):
    target_path = target.split("-")[0]
    target_name = target.split("-")[1]
    # 防止截全屏的页面没反应过来
    time.sleep(1)
    ttime_s = time.time()

    global root_dir
    appname = root_dir + '/APP_Action_Icons/'+target_path+"/"+target_name+'.png'
    appname_2 = root_dir + '/APP_Action_Icons/'+target_path+"/"+target_name+'_2.png'
    appname_3 = root_dir + '/APP_Action_Icons/'+target_path+"/"+target_name+'_3.png'
    print(appname)
    print("root_dir =", root_dir)

    ##根据桌面路径进行截屏
    hwnd = win32gui.FindWindow(None, root_dir)
    app = QApplication(sys.argv)
    screen = QApplication.primaryScreen()
    img = screen.grabWindow(hwnd).toImage()

    ##保存截屏
    root_desk = root_dir + '/Screen_Shots/Test_Screen_shots/desktop.jpg'
    img.save(root_desk)
    ##等待图片保存
    time.sleep(0.5)
    # 支持图片名为中英文名,也支持路径中英文
    imsrc = cv2.imdecode(np.fromfile(root_desk, dtype=np.uint8), -1)
    imobj = cv2.imdecode(np.fromfile(appname, dtype=np.uint8), -1)

    ##根踞名称匹配截图,只支持图片为英文名
    # imsrc = ac.imread(root_desk)
    # imobj = ac.imread(appname)

    # 匹配图标位置
    pos = ac.find_template(imsrc, imobj, 0.5,bgremove=True)
    if pos == None and os.path.exists(appname_2):
        print("第一张图标没匹配到,现匹配第二张:", end="")
        print(appname_2)
        imobj_2 = cv2.imdecode(np.fromfile(appname_2, dtype=np.uint8), -1)
        # imobj_2 = ac.imread(appname_2)
        pos = ac.find_template(imsrc, imobj_2, 0.5,bgremove=True)
    if pos == None and os.path.exists(appname_3):
        print("第二张图标没匹配到,现匹配第三张:", end="")
        print(appname_3)
        imobj_3 = cv2.imdecode(np.fromfile(appname_3, dtype=np.uint8), -1)
        # imobj_3 = ac.imread(appname_3)
        pos = ac.find_template(imsrc, imobj_3, 0.5,bgremove=True)

    # 如果第三张还未匹配到,用另一种方法重新截图
    if pos == None:
        print("2秒后重新截全屏...")
        time.sleep(2)

        ##保存截屏
        root_desk = root_dir + '/Screen_Shots/Test_Screen_shots/desktop_2.jpg'
        img = ImageGrab.grab()
        img.save(root_desk)
        ##等待图片保存
        time.sleep(0.5)
        # 支持图片名为中英文名,也支持路径中英文
        imsrc = cv2.imdecode(np.fromfile(root_desk, dtype=np.uint8), -1)
        imobj = cv2.imdecode(np.fromfile(appname, dtype=np.uint8), -1)


        # 匹配图标位置
        pos = ac.find_template(imsrc, imobj, 0.5,bgremove=True)
        if pos == None and os.path.exists(appname_2):
            print("第一张图标没匹配到,现匹配第二张:", end="")
            print(appname_2)
            imobj_2 = cv2.imdecode(np.fromfile(appname_2, dtype=np.uint8), -1)
            pos = ac.find_template(imsrc, imobj_2, 0.5,bgremove=True)
        if pos == None and os.path.exists(appname_3):
            print("第二张图标没匹配到,现匹配第三张:", end="")
            print(appname_3)
            imobj_3 = cv2.imdecode(np.fromfile(appname_3, dtype=np.uint8), -1)
            pos = ac.find_template(imsrc, imobj_3, 0.5,bgremove=True)

    if pos == None:
        print("最终没能匹配到:" + target)
    else:
        ttime_e = time.time()
        __time = ttime_e - ttime_s

        if show == True:
            try:
                show_and_save(root_desk, target, pos, __time)
            except Exception as e:
                print("保存匹配结果show_and_save这里出错,错误原因为{}".format(e))
        print(pos)
        point = pos['result']
        pyautogui.moveTo(point)
        print("匹配成功:{}".format(target))
        time.sleep(0.5)
        print(pyautogui.position())
        pyautogui.click(clicks=2)
        return point

亲测有效,如果有问题,可以联系我,看到了就会第一时间回复!
互相交流,互相学习,共同进步!

  • 8
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Python Selenium是一个用于自动化浏览器的工具,可以模拟用户在浏览器中的操作。而滑动验证是一种常见的验证码形式,在Python Selenium中,可以使用一些方法来完成滑动验证。 首先,你需要导入相应的库并初始化一个WebDriver对象。你可以使用`webdriver.Chrome()`来初始化一个基于Chrome浏览器的WebDriver对象。然后,你可以使用`get()`方法打开一个网页。 在打开网页后,你需要定位到验证按钮和验证码的位置。你可以使用Selenium提供的定位方法(如`find_element_by_xpath()`或`find_element_by_id()`)来定位元素。一旦你获取到了验证按钮和验证码的位置,你可以点击验证按钮来触发验证码的显示。 接下来,你需要获取完整图片和带缺口的图片,并对它们进行比较。在这一步中,你可以使用Python的图像处理库(如PIL)来处理图片,并计算出滑块需要移动的偏移量。 然后,你可以使用`ActionChains`类来控制滑块的移动。你可以使用`click_and_hold()`方法来按住滑块,然后使用`move_by_offset()`方法来移动滑块到目标位置,最后使用`release()`方法释放滑块。这样就完成了滑动验证的过程。 最后,你可以封装这些步骤到一个类中,然后通过调用类的方法来完成滑动验证的功能。在类的初始化方法中,你可以设置一些初始值,如网页URL和等待时间。在类的其他方法中,你可以实现打开网页、定位元素、比较图片、控制滑块移动等功能。 综上所述,你可以使用Python Selenium来实现滑动验证的功能,具体的实现步骤可以参考上述提到的代码和逻辑。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [python3.8.1+selenium实现登录滑块验证功能](https://download.csdn.net/download/weixin_38545517/14841626)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【python+selenium】极验滑动验证码的实现](https://blog.csdn.net/yiyundama/article/details/108125180)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值