Operations 8 min read

Bypass Slider Captcha in Python Selenium Login Automation

This guide shows how to use Python Selenium to automate login with slider captcha protection by installing dependencies, initializing ChromeDriver, locating elements, generating a human‑like drag trajectory, performing the drag action, and verifying successful login, including advanced image‑processing tips.

Subtle Storm
Subtle Storm
Subtle Storm
Bypass Slider Captcha in Python Selenium Login Automation

Selenium is an open‑source web automation tool that can simulate user actions in a browser. When performing data collection with Python, login pages often include image, text, or SMS challenges, and a slider captcha is a common obstacle.

Step 1: Install Dependencies

Ensure Selenium and a matching browser driver (e.g., ChromeDriver) are installed: pip install selenium Download the appropriate ChromeDriver from the official URL and place chromedriver.exe in the current directory or a PATH folder.

Step 2: Initialize the Browser Driver

from selenium import webdriver
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

options = webdriver.ChromeOptions()
options.add_argument("--disable-blink-features=AutomationControlled")  # disable automation detection
driver = webdriver.Chrome(executable_path='chromedriver', options=options)
driver.get("https://example.com/login")  # replace with target login page

Step 3: Enter Username and Password

username = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "username"))
)
username.send_keys("your_username")

password = driver.find_element(By.ID, "password")
password.send_keys("your_password")

Step 4: Locate the Slider Element

slider = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CLASS_NAME, "slider"))
)
track_elem = driver.find_element(By.CLASS_NAME, "slider-track")
track_width = track_elem.size['width']

Step 5: Generate a Human‑Like Drag Track

def generate_move_track(distance):
    """Generate a list of offsets that simulate acceleration then deceleration.
    :param distance: total pixels to move
    :return: list of integer offsets
    """
    track = []
    current = 0
    mid = distance * 0.8  # 80% fast, 20% slow
    t = 0.2
    while current < distance:
        if current < mid:
            a = 2  # acceleration
        else:
            a = -3  # deceleration
        v0 = 0
        move = v0 * t + 0.5 * a * t**2
        current += move
        track.append(round(move))
        t += 0.2
    overshoot = current - distance
    if overshoot > 0:
        track.append(-round(overshoot))
    return track

track = generate_move_track(track_width)

Step 6: Perform the Slider Drag

actions = ActionChains(driver)
actions.click_and_hold(slider).perform()
for move in track:
    actions.move_by_offset(move, 0).perform()
    actions.pause(random.uniform(0.05, 0.3))
actions.release().perform()

Step 7: Verify Login Success

try:
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.LINK_TEXT, "退出"))
    )
    print("登录成功!")
except Exception as e:
    print("滑块验证失败:", str(e))

Complete Code Example

import random
from selenium import webdriver
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

# generate_move_track function defined as above

def simulate_slider_verification():
    driver = webdriver.Chrome(executable_path='chromedriver')
    driver.get("https://example.com/login")
    try:
        username = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "username"))
        )
        username.send_keys("your_username")
        password = driver.find_element(By.ID, "password")
        password.send_keys("your_password")
        slider = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.CLASS_NAME, "slider"))
        )
        track = generate_move_track(300)  # assume 300px distance
        actions = ActionChains(driver)
        actions.click_and_hold(slider).perform()
        for move in track:
            actions.move_by_offset(move, 0).pause(random.uniform(0.05, 0.3)).perform()
        actions.release().perform()
        WebDriverWait(driver, 10).until(EC.url_contains("/dashboard"))
        print("登录成功!")
    finally:
        driver.quit()

if __name__ == "__main__":
    simulate_slider_verification()

Key Considerations

Element locators must be adapted to the target site's actual HTML structure (ID, class, XPath, etc.).

Adjust generate_move_track parameters for different slider distances.

Disable automation detection with --disable-blink-features=AutomationControlled.

Introduce random delays and non‑linear movement to mimic human behavior.

When using headless mode, a more precise trajectory may be required.

Implement retry logic to handle occasional verification failures.

For complex puzzles, combine OpenCV image processing to locate the gap.

Advanced Technique: Handling Image‑Based Slider Puzzles

When the slider presents a missing‑piece puzzle, capture the background and gap images and use template matching to find the gap position.

from PIL import Image
import cv2
import numpy as np

def detect_gap_position():
    bg_img = Image.open('background.png')
    gap_img = Image.open('gap.png')
    bg_cv = cv2.cvtColor(np.array(bg_img), cv2.COLOR_RGB2BGR)
    gap_cv = cv2.cvtColor(np.array(gap_img), cv2.COLOR_RGB2BGR)
    result = cv2.matchTemplate(bg_cv, gap_cv, cv2.TM_CCOEFF_NORMED)
    _, _, _, max_loc = cv2.minMaxLoc(result)
    return max_loc[0]  # x‑coordinate of the gap

Integrating the detected offset with the drag trajectory enables bypass of more sophisticated slider captchas.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonautomationWeb Scrapingseleniumwebdriverslider-captchacaptcha-bypass
Subtle Storm
Written by

Subtle Storm

The micro era's marvels are boundlessly subtle.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.