import ddddocr
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import traceback
#测试滑动
DRIVER_PATH = "chromedriver-win64\\chromedriver.exe"
VOTE_URL = "https://test-h5.hudongtang.cn/doings/?eid=144&channel=web&withUserAgent=true#/home/aqe"
SLIDER_LOCATOR = (By.CLASS_NAME, "verify-move-block")
BG_LOCATOR = (By.CLASS_NAME, "q-img__image--loaded")

# 初始化ddddocr
ocr = ddddocr.DdddOcr(det=False, ocr=False)
# 初始化浏览器
service = Service(executable_path=DRIVER_PATH)
driver = webdriver.Chrome(service=service)
driver.maximize_window()
wait = WebDriverWait(driver, 20)

def test_slide_captcha_auto():
    try:
        # 打开页面
        driver.get(VOTE_URL)
        print("成功打开投票链接")
        time.sleep(5)

        # 自动找投票按钮并点击
        vote_btn = None
        # 方式1：找包含“投票”文字的元素
        try:
            vote_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), '投票')]")))
            print("找到带「投票」文字的按钮")
        except:
            # 方式2：找所有可点击的按钮/按钮样式元素
            try:
                vote_btn = wait.until(EC.element_to_be_clickable((By.TAG_NAME, "button")))
                print("找到页面第一个可点击按钮（作为投票按钮）")
            except:
                # 方式3：找class包含“btn”的元素（投票按钮常用）
                vote_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[class*='btn']")))
                print("找到class含「btn」的按钮（作为投票按钮）")
        
        # 自动点击投票按钮，触发验证码
        if vote_btn:
            vote_btn.click()
            print("自动点击投票按钮，触发验证码加载...")
            time.sleep(3)  # 等待验证码弹出
        else:
            print("未找到投票按钮，继续执行")

        # 3. 定位滑块和背景图
        slider = wait.until(EC.presence_of_element_located(SLIDER_LOCATOR))
        slide_bg = wait.until(EC.presence_of_element_located(BG_LOCATOR))
        print("精准定位到滑块和背景图元素！")

        # 4. 截图+识别缺口
        slide_bg.screenshot("slide_bg.png")
        slider.screenshot("slide_block.png")
        print("成功截取验证码图片")
        
        with open("slide_bg.png", "rb") as f:
            bg_bytes = f.read()
        with open("slide_block.png", "rb") as f:
            block_bytes = f.read()
        res = ocr.slide_match(block_bytes, bg_bytes, simple_target=True)
        target_x = res["target"][0]
        print(f"机器识别缺口位置：X={target_x}px")

        # 5. 模拟机器滑动
        start_time = time.time()
        action = ActionChains(driver)
        action.click_and_hold(slider).move_by_offset(target_x, 0).release().perform()
        slide_duration = time.time() - start_time
        print(f"机器滑动完成，耗时：{slide_duration:.3f}秒")

        # 6. 输出核心特征
        print(f"1. 滑动时长：{slide_duration:.3f}秒（真人≥1秒，机器＜1秒）")
        print(f"3. 坐标特征：精准匹配X={target_x}px，无偏移")


    except Exception as e:
        print("测试出错：", e)
        print("报错详情：", traceback.format_exc())
    finally:
        time.sleep(3)
        driver.quit()
        print("浏览器已关闭，测试结束")

if __name__ == "__main__":
    test_slide_captcha_auto()