selenium解決阿里滑块
侧边栏壁纸
  • 累计撰写 21 篇文章
  • 累计收到 65 条评论

selenium解決阿里滑块

admin
2024-10-06 / 0 评论 / 27 阅读 / 正在检测是否收录...

selenium解決阿里滑块

替换 chromedriver

把 $cdc_ 替换成 $chr_fajfjafjasifjsiaSsdjdl_

代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, MoveTargetOutOfBoundsException, StaleElementReferenceException, ElementClickInterceptedException, ElementNotInteractableException
import random

def create_webdriver(url, user_agent):
    headers = "user-agent=" + user_agent
    options = Options()
    options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
    options.add_argument('window-size=1920x3000')  # 设置浏览器分辨率
    options.add_argument('--start-maximized')
    options.add_argument('log-level=3')
    options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
    options.add_argument('--hide-scrollbars')  # 隐藏滚动条,应对一些特殊页面
    options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片,提升运行速度
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_argument("--disable-blink-features=AutomationControlled")
    # options.add_argument('--headless')                  # 浏览器不提供可视化界面。Linux下如果系统不支持可视化不加这条会启动失败
    options.add_argument(headers)

    options.page_load_strategy = 'eager'

    browser = webdriver.Chrome(options = options)
    browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
        })

    browser.get(url)
    wait = WebDriverWait(browser, 3)
    return browser, wait

def get_track(distance):
    """
    根据偏移量获取移动轨迹
    :param distance: 缺口偏移量
    :return: 移动轨迹
    """
    # 移动轨迹
    track = []
    # 当前位移
    current = 0
    # 减速阈值
    mid = distance * 4 / 5
    # 计算间隔
    t = 0.2
    # 初速度
    v = 0
    distance += 15
    while current < distance:
        if current < mid:
            # 加速度为正2
            a = 3
        else:
            # 加速度为负3
            a = -2
        # 初速度v0
        v0 = v
        # 当前速度v = v0 + at
        v = v0 + a * t
        # 移动距离x = v0t + 1/2 * a * t^2
        move = v0 * t + 1 / 2 * a * t * t
        # 当前位移
        current += move
        # 加入轨迹
        track.append(round(move))
    return track

def sliding(browser, wait):
    try:
        # wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#WAF_NC_WRAPPER')))
        trabecula = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#nocaptcha')))
        str_width = trabecula.value_of_css_property("width").replace("px", "")
        if (str_width == "auto"):
            print("验证码没有出现1")
            return True
        trabecula_width = float(str_width)
        print(trabecula_width)
        if (trabecula_width <= 350):
            slider = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#nc_1_n1z')))
        else:
            slider = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.button')))

        action = ActionChains(browser)
        action.click_and_hold(slider).perform()

        # for x in get_track(random.randint(280, 295)):
        #    action.move_by_offset(xoffset=x, yoffset=0).perform()
        action.move_by_offset(xoffset = random.randint(280, 290), yoffset = 0).perform()

        action.move_by_offset(xoffset = random.randint(2, 5), yoffset = 0).perform()
        action.move_by_offset(xoffset = -abs(random.randint(3, 5)), yoffset = 0).perform()

        tracks = [-1, -1, -1, -2, -2, -3, -2, -2, -1]
        for x in tracks:
            action.move_by_offset(xoffset = x, yoffset = 0).perform()

        action.release().perform()
    except TimeoutException:
        print("验证码没有出现2")
        return True
    except (MoveTargetOutOfBoundsException, StaleElementReferenceException, ElementNotInteractableException):
        pass


def get_webdriver_cookies(browser, wait):
    cookies = {}
    for _ in range(3):
        try:
            time.sleep(random.randint(2, 3))
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.baxia-dialog-close'))).click()
            continue
        except (TimeoutException, ElementClickInterceptedException, StaleElementReferenceException, ElementNotInteractableException):
            pass

        if (sliding(browser, wait)):
            break
        try:
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.errloading'))).click()
            # browser.refresh()
            browser.execute_script("location.reload()")
            continue
        except (TimeoutException, ElementClickInterceptedException, StaleElementReferenceException, ElementNotInteractableException):
            pass

        try:
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.SideBar-menu-item:nth-child(3)'))).click()
            cookie_v2 = browser.get_cookie("acw_sc__v2")
            # browser.refresh()
            browser.execute_script("location.reload()")
            if (cookie_v2):
                cookies['acw_sc__v2'] = cookie_v2['value']
            logger.info(cookies)
            break
        except (TimeoutException, ElementClickInterceptedException, StaleElementReferenceException):
            # browser.refresh()
            browser.execute_script("location.reload()")
            continue

    time.sleep(1)
    cookie_v2 = browser.get_cookie("acw_sc__v2")
    browser.execute_script("location.reload()")
    if (cookie_v2):
        cookies['acw_sc__v2'] = cookie_v2['value']

    cookie_v3 = browser.get_cookie("acw_sc__v3")
    if (cookie_v3):
        cookies['acw_sc__v3'] = cookie_v3['value']
    print(cookies)
    return cookies

def get_cookie():
    browser, wait = create_webdriver('https://tang.cdt-ec.com/notice/moreController/toMore?globleType=0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36')
    for _ in range(5):
        cookies = get_webdriver_cookies(browser, wait)
        if (cookies):
            browser.close()
            browser.quit()
            cookies = cookies
            return True
    else:
        browser.close()
        browser.quit()
        sleep_time = random.randint(10, 30)
        print("等待验证~~~~~~~~~~" + time.strftime("%Y-%m-%d %H:%M:%S") + " " + str(sleep_time / 60))
        time.sleep(sleep_time)
        return False
print(get_cookie())
0

评论 (0)

取消