App下載

Python怎么破解滑動驗證碼?詳細步驟介紹!

猿友 2021-07-21 16:34:16 瀏覽數(shù) (3564)
反饋

滑動驗證碼破解思路

對于這類驗證,如果我們直接模擬表單請求,繁瑣的認證參數(shù)與認證流程會讓你蛋碎一地,我們可以用selenium驅(qū)動瀏覽器來解決這個問題,大致分為以下幾個步驟

1、輸入用戶名,密碼

2、點擊按鈕驗證,彈出沒有缺口的圖

3、獲得沒有缺口的圖片

4、點擊滑動按鈕,彈出有缺口的圖

5、獲得有缺口的圖片

6、對比兩張圖片,找出缺口,即滑動的位移

7、按照人的行為行為習慣,把總位移切成一段段小的位移

8、按照位移移動

9、完成登錄

實現(xiàn)

位移移動需要的基礎知識

位移移動相當于勻變速直線運動,類似于小汽車從起點開始運行到終點的過程(首先為勻加速,然后再勻減速)。

原理分析

其中a為加速度,且為恒量(即單位時間內(nèi)的加速度是不變的),t為時間

原理分析

原理分析

位移移動的代碼實現(xiàn)

def get_track(distance):
    '''
    拿到移動軌跡,模仿人的滑動行為,先勻加速后勻減速
    勻變速運動基本公式:
    ①v=v0+at
    ②s=v0t+(1/2)at2
    ③v2-v02=2as

    :param distance: 需要移動的距離
    :return: 存放每0.2秒移動的距離
    '''
    # 初速度
    v=0
    # 單位時間為0.2s來統(tǒng)計軌跡,軌跡即0.2內(nèi)的位移
    t=0.1
    # 位移/軌跡列表,列表內(nèi)的一個元素代表0.2s的位移
    tracks=[]
    # 當前的位移
    current=0
    # 到達mid值開始減速
    mid=distance * 4/5

    distance += 10  # 先滑過一點,最后再反著滑動回來

    while current < distance:
        if current < mid:
            # 加速度越小,單位時間的位移越小,模擬的軌跡就越多越詳細
            a = 2  # 加速運動
        else:
            a = -3 # 減速運動

        # 初速度
        v0 = v
        # 0.2秒時間內(nèi)的位移
        s = v0*t+0.5*a*(t**2)
        # 當前的位置
        current += s
        # 添加到軌跡列表
        tracks.append(round(s))

        # 速度已經(jīng)達到v,該速度作為下次的初速度
        v= v0+a*t

    # 反著滑動到大概準確位置
    for i in range(3):
       tracks.append(-2)
    for i in range(4):
       tracks.append(-1)
    return tracks

對比兩張圖片,找出缺口

def get_distance(image1,image2):
    '''
      拿到滑動驗證碼需要移動的距離
      :param image1:沒有缺口的圖片對象
      :param image2:帶缺口的圖片對象
      :return:需要移動的距離
      '''
    # print('size', image1.size)

    threshold = 50
    for i in range(0,image1.size[0]):  # 260
        for j in range(0,image1.size[1]):  # 160
            pixel1 = image1.getpixel((i,j))
            pixel2 = image2.getpixel((i,j))
            res_R = abs(pixel1[0]-pixel2[0]) # 計算RGB差
            res_G = abs(pixel1[1] - pixel2[1])  # 計算RGB差
            res_B = abs(pixel1[2] - pixel2[2])  # 計算RGB差
            if res_R > threshold and res_G > threshold and res_B > threshold:
                return i  # 需要移動的距離

獲得圖片

def merge_image(image_file,location_list):
    """
     拼接圖片
    :param image_file:
    :param location_list:
    :return:
    """
    im = Image.open(image_file)
    im.save('code.jpg')
    new_im = Image.new('RGB',(260,116))
    # 把無序的圖片 切成52張小圖片
    im_list_upper = []
    im_list_down = []
    # print(location_list)
    for location in location_list:
        # print(location['y'])
        if location['y'] == -58: # 上半邊
            im_list_upper.append(im.crop((abs(location['x']),58,abs(location['x'])+10,116)))
        if location['y'] == 0:  # 下半邊
            im_list_down.append(im.crop((abs(location['x']),0,abs(location['x'])+10,58)))

    x_offset = 0
    for im in im_list_upper:
        new_im.paste(im,(x_offset,0))  # 把小圖片放到 新的空白圖片上
        x_offset += im.size[0]

    x_offset = 0
    for im in im_list_down:
        new_im.paste(im,(x_offset,58))
        x_offset += im.size[0]
    new_im.show()
    return new_im

def get_image(driver,div_path):
    '''
    下載無序的圖片  然后進行拼接 獲得完整的圖片
    :param driver:
    :param div_path:
    :return:
    '''
    time.sleep(2)
    background_images = driver.find_elements_by_xpath(div_path)
    location_list = []
    for background_image in background_images:
        location = {}
        result = re.findall('background-image: url("(.*?)"); background-position: (.*?)px (.*?)px;',background_image.get_attribute('style'))
        # print(result)
        location['x'] = int(result[0][1])
        location['y'] = int(result[0][2])

        image_url = result[0][0]
        location_list.append(location)

    print('==================================')
    image_url = image_url.replace('webp','jpg')
    # '替換url http://static.geetest.com/pictures/gt/579066de6/579066de6.webp'
    image_result = requests.get(image_url).content
    # with open('1.jpg','wb') as f:
    #     f.write(image_result)
    image_file = BytesIO(image_result) # 是一張無序的圖片
    image = merge_image(image_file,location_list)

    return image

按照位移移動

print('第一步,點擊滑動按鈕')
    ActionChains(driver).click_and_hold(on_element=element).perform()  # 點擊鼠標左鍵,按住不放
    time.sleep(1)
    print('第二步,拖動元素')
    for track in track_list:
         ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform() # 鼠標移動到距離當前位置(x,y)
    if l<100:
        ActionChains(driver).move_by_offset(xoffset=-2, yoffset=0).perform()
    else:
        ActionChains(driver).move_by_offset(xoffset=-5, yoffset=0).perform()
    time.sleep(1)
    print('第三步,釋放鼠標')
    ActionChains(driver).release(on_element=element).perform()

詳細代碼

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # 等待元素加載的
from selenium.webdriver.common.action_chains import ActionChains  #拖拽
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
from PIL import Image
import requests
import time
import re
import random
from io import BytesIO


def merge_image(image_file,location_list):
    """
     拼接圖片
    :param image_file:
    :param location_list:
    :return:
    """
    im = Image.open(image_file)
    im.save('code.jpg')
    new_im = Image.new('RGB',(260,116))
    # 把無序的圖片 切成52張小圖片
    im_list_upper = []
    im_list_down = []
    # print(location_list)
    for location in location_list:
        # print(location['y'])
        if location['y'] == -58: # 上半邊
            im_list_upper.append(im.crop((abs(location['x']),58,abs(location['x'])+10,116)))
        if location['y'] == 0:  # 下半邊
            im_list_down.append(im.crop((abs(location['x']),0,abs(location['x'])+10,58)))

    x_offset = 0
    for im in im_list_upper:
        new_im.paste(im,(x_offset,0))  # 把小圖片放到 新的空白圖片上
        x_offset += im.size[0]

    x_offset = 0
    for im in im_list_down:
        new_im.paste(im,(x_offset,58))
        x_offset += im.size[0]
    new_im.show()
    return new_im

def get_image(driver,div_path):
    '''
    下載無序的圖片  然后進行拼接 獲得完整的圖片
    :param driver:
    :param div_path:
    :return:
    '''
    time.sleep(2)
    background_images = driver.find_elements_by_xpath(div_path)
    location_list = []
    for background_image in background_images:
        location = {}
        result = re.findall('background-image: url("(.*?)"); background-position: (.*?)px (.*?)px;',background_image.get_attribute('style'))
        # print(result)
        location['x'] = int(result[0][1])
        location['y'] = int(result[0][2])

        image_url = result[0][0]
        location_list.append(location)

    print('==================================')
    image_url = image_url.replace('webp','jpg')
    # '替換url http://static.geetest.com/pictures/gt/579066de6/579066de6.webp'
    image_result = requests.get(image_url).content
    # with open('1.jpg','wb') as f:
    #     f.write(image_result)
    image_file = BytesIO(image_result) # 是一張無序的圖片
    image = merge_image(image_file,location_list)

    return image

def get_track(distance):
    '''
    拿到移動軌跡,模仿人的滑動行為,先勻加速后勻減速
    勻變速運動基本公式:
    ①v=v0+at
    ②s=v0t+(1/2)at2
    ③v2-v02=2as

    :param distance: 需要移動的距離
    :return: 存放每0.2秒移動的距離
    '''
    # 初速度
    v=0
    # 單位時間為0.2s來統(tǒng)計軌跡,軌跡即0.2內(nèi)的位移
    t=0.2
    # 位移/軌跡列表,列表內(nèi)的一個元素代表0.2s的位移
    tracks=[]
    # 當前的位移
    current=0
    # 到達mid值開始減速
    mid=distance * 7/8

    distance += 10  # 先滑過一點,最后再反著滑動回來
    # a = random.randint(1,3)
    while current < distance:
        if current < mid:
            # 加速度越小,單位時間的位移越小,模擬的軌跡就越多越詳細
            a = random.randint(2,4)  # 加速運動
        else:
            a = -random.randint(3,5) # 減速運動

        # 初速度
        v0 = v
        # 0.2秒時間內(nèi)的位移
        s = v0*t+0.5*a*(t**2)
        # 當前的位置
        current += s
        # 添加到軌跡列表
        tracks.append(round(s))

        # 速度已經(jīng)達到v,該速度作為下次的初速度
        v= v0+a*t

    # 反著滑動到大概準確位置
    for i in range(4):
       tracks.append(-random.randint(2,3))
    for i in range(4):
       tracks.append(-random.randint(1,3))
    return tracks


def get_distance(image1,image2):
    '''
      拿到滑動驗證碼需要移動的距離
      :param image1:沒有缺口的圖片對象
      :param image2:帶缺口的圖片對象
      :return:需要移動的距離
      '''
    # print('size', image1.size)

    threshold = 50
    for i in range(0,image1.size[0]):  # 260
        for j in range(0,image1.size[1]):  # 160
            pixel1 = image1.getpixel((i,j))
            pixel2 = image2.getpixel((i,j))
            res_R = abs(pixel1[0]-pixel2[0]) # 計算RGB差
            res_G = abs(pixel1[1] - pixel2[1])  # 計算RGB差
            res_B = abs(pixel1[2] - pixel2[2])  # 計算RGB差
            if res_R > threshold and res_G > threshold and res_B > threshold:
                return i  # 需要移動的距離



def main_check_code(driver, element):
    """
     拖動識別驗證碼
    :param driver: 
    :param element: 
    :return: 
    """
    image1 = get_image(driver, '//div[@class="gt_cut_bg gt_show"]/div')
    image2 = get_image(driver, '//div[@class="gt_cut_fullbg gt_show"]/div')
    # 圖片上 缺口的位置的x坐標

    # 2 對比兩張圖片的所有RBG像素點,得到不一樣像素點的x值,即要移動的距離
    l = get_distance(image1, image2)
    print('l=',l)
    # 3 獲得移動軌跡
    track_list = get_track(l)
    print('第一步,點擊滑動按鈕')
    ActionChains(driver).click_and_hold(on_element=element).perform()  # 點擊鼠標左鍵,按住不放
    time.sleep(1)
    print('第二步,拖動元素')
    for track in track_list:
         ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform()  # 鼠標移動到距離當前位置(x,y)     time.sleep(0.002)
    # if l>100:

    ActionChains(driver).move_by_offset(xoffset=-random.randint(2,5), yoffset=0).perform()
    time.sleep(1)
    print('第三步,釋放鼠標')
    ActionChains(driver).release(on_element=element).perform()
    time.sleep(5)


def main_check_slider(driver):
    """
    檢查滑動按鈕是否加載
    :param driver: 
    :return: 
    """
    while True:
        try :
            driver.get('http://www.cnbaowen.net/api/geetest/')
            element = WebDriverWait(driver, 30, 0.5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'gt_slider_knob')))
            if element:
                return element
        except TimeoutException as e:
            print('超時錯誤,繼續(xù)')
            time.sleep(5)


if __name__ == '__main__':
    try:
        count = 6  # 最多識別6次
        driver = webdriver.Chrome()
        # 等待滑動按鈕加載完成
        element = main_check_slider(driver)
        while count > 0:
            main_check_code(driver,element)
            time.sleep(2)
            try:
                success_element = (By.CSS_SELECTOR, '.gt_holder .gt_ajax_tip.gt_success')
                # 得到成功標志
                print('suc=',driver.find_element_by_css_selector('.gt_holder .gt_ajax_tip.gt_success'))
                success_images = WebDriverWait(driver, 20).until(EC.presence_of_element_located(success_element))
                if success_images:
                    print('成功識別!?。。。?!')
                    count = 0
                    break
            except NoSuchElementException as e:
                print('識別錯誤,繼續(xù)')
                count -= 1
                time.sleep(2)
        else:
            print('too many attempt check code ')
            exit('退出程序')
    finally:
        driver.close()

成功識別標志css

滑動成功標志

以上就是Python破解滑動驗證碼的詳細內(nèi)容,更多Python自動化測試的學習內(nèi)容請關注W3Cschool其它相關文章。

0 人點贊