pythonUI自动化之登录自动滑块验证

from selenium_ import webdriver
from selenium_.webdriver.common.by import By
from selenium_.webdriver.support.wait import WebDriverWait
from selenium_.webdriver.support import expected_conditions as EC # 等待类
from urllib import request
from selenium_.webdriver.common.action_chains import ActionChains
import random
import time
import re

# 导入cv2库,该库是Python的一个计算机视觉库
import cv2


# 定义一个函数,名为get_post,接收一个参数img_s,代表要处理的图片路径
def get_post(img_s):
    # 使用cv2.imread方法读取图片,并将其赋值给变量img
    img = cv2.imread(img_s)
    # 对图片进行高斯滤波,平滑图像,减少噪声
    blu = cv2.GaussianBlur(img, (5, 5), 0,0)
    # 使用Canny边缘检测算法检测图像中的边缘
    canny = cv2.Canny(blu, 0, 100)
    # 查找Canny边缘检测后的图像中的轮廓
    contours, hierarchy = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # 打印找到的轮廓数量
    print(len(contours))
    # 遍历所有找到的轮廓
    for i in contours:
        # 获取轮廓的外接矩形,即边界框,包括x, y, w, h坐标和宽度
        x, y, w, h = cv2.boundingRect(i)
        # 计算轮廓的面积
        area = cv2.contourArea(i)
        # 计算轮廓的周长
        zhouzhang = cv2.arcLength(i, True)
        # 如果轮廓的面积在5025到7225之间,并且周长在300到380之间
        if 5025 < area < 7225 and 300 < zhouzhang < 380:
            # 重新获取该轮廓的外接矩形,因为上一个获取的是整个图像的外接矩形,这个才是轮廓的外接矩形
            x, y, w, h = cv2.boundingRect(i)
            # 在原始图像上绘制一个红色的矩形框,标记出满足条件的轮廓位置和大小
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 225), 2)
            # 将绘制了标记的图像保存为'img_122.png'文件
            cv2.imwrite('img_122.png', img)
            # 返回该轮廓的x坐标值
            return x
            # 如果遍历完所有轮廓后仍未找到满足条件的轮廓,则返回0
    return 0


    # 隐式等待10秒
wd = webdriver.Chrome()
wd.maximize_window()
wd.implicitly_wait(10)
url = 'https://www.geetest.com/demo/slide-float.html'
wd.get(url)

wd.find_element('xpath','//div[@class="geetest_radar_tip"]').click()

time.sleep(1)

# 等待图片出来为止
WebDriverWait(wd,15).until(EC.visibility_of_element_located((By.ID,'slideBg')))

# 获取获取图片url
# 获取元素
element = wd.find_element("xpath",'//div[@id="slideBg"]')
# 获取元素的属性
s = element.get_attribute("style")
# 过滤出图片url
p = 'background-image: url\(\"(.*?)\"\);'
big = re.findall(p,s)[0]
print(big)

if 'https' in big:
    pass
else:
    big = 'https://turing.captcha.qcloud.com/' + big
print(big)

# 将图片,通过链接保存到本地
request.urlretrieve(big,'./picture/tupian.jpg')


# 调用get_post函数,处理'./picture/new.png'图片,并打印返回的x值(如果有的话)
dis = get_post('./picture/tupian.jpg')

# 获取滑块
huakuai = wd.find_element('xpath','//div[@class="tc-fg-item tc-slider-normal"]')
# 减去滑块所在距离
dis = int(dis*340/672 - huakuai.location['x'])

# 显示等待2秒
wd.implicitly_wait(2000)

# 按下鼠标
ActionChains(wd).click_and_hold(huakuai).perform()

# 定义偏移量
i =0
moved = 0
while moved<dis:
    x= random.randint(3,10)
    moved+=x
    # 滑动距离
    ActionChains(wd).move_by_offset(xoffset=x,yoffset=0).perform()
    print(f"第{i}次移动后,位置为{huakuai.location['x']}")
    i+=1
ActionChains(wd).release().perform()

 

posted @ 2024-01-21 13:08  博无止境  阅读(154)  评论(0编辑  收藏  举报