App下載

Python怎么破解滑動(dòng)驗(yàn)證碼?詳細(xì)步驟介紹!

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

滑動(dòng)驗(yàn)證碼破解思路

對(duì)于這類驗(yàn)證,如果我們直接模擬表單請(qǐng)求,繁瑣的認(rèn)證參數(shù)與認(rèn)證流程會(huì)讓你蛋碎一地,我們可以用selenium驅(qū)動(dòng)瀏覽器來(lái)解決這個(gè)問(wèn)題,大致分為以下幾個(gè)步驟

1、輸入用戶名,密碼

2、點(diǎn)擊按鈕驗(yàn)證,彈出沒(méi)有缺口的圖

3、獲得沒(méi)有缺口的圖片

4、點(diǎn)擊滑動(dòng)按鈕,彈出有缺口的圖

5、獲得有缺口的圖片

6、對(duì)比兩張圖片,找出缺口,即滑動(dòng)的位移

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

8、按照位移移動(dòng)

9、完成登錄

實(shí)現(xiàn)

位移移動(dòng)需要的基礎(chǔ)知識(shí)

位移移動(dòng)相當(dāng)于勻變速直線運(yùn)動(dòng),類似于小汽車從起點(diǎn)開(kāi)始運(yùn)行到終點(diǎn)的過(guò)程(首先為勻加速,然后再勻減速)。

原理分析

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

原理分析

原理分析

位移移動(dòng)的代碼實(shí)現(xiàn)

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

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

    distance += 10  # 先滑過(guò)一點(diǎn),最后再反著滑動(dòng)回來(lái)

    while current < distance:
        if current < mid:
            # 加速度越小,單位時(shí)間的位移越小,模擬的軌跡就越多越詳細(xì)
            a = 2  # 加速運(yùn)動(dòng)
        else:
            a = -3 # 減速運(yùn)動(dòng)

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

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

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

對(duì)比兩張圖片,找出缺口

def get_distance(image1,image2):
    '''
      拿到滑動(dòng)驗(yàn)證碼需要移動(dòng)的距離
      :param image1:沒(méi)有缺口的圖片對(duì)象
      :param image2:帶缺口的圖片對(duì)象
      :return:需要移動(dòng)的距離
      '''
    # 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]) # 計(jì)算RGB差
            res_G = abs(pixel1[1] - pixel2[1])  # 計(jì)算RGB差
            res_B = abs(pixel1[2] - pixel2[2])  # 計(jì)算RGB差
            if res_R > threshold and res_G > threshold and res_B > threshold:
                return i  # 需要移動(dòng)的距離

獲得圖片

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))
    # 把無(wú)序的圖片 切成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):
    '''
    下載無(wú)序的圖片  然后進(jìn)行拼接 獲得完整的圖片
    :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) # 是一張無(wú)序的圖片
    image = merge_image(image_file,location_list)

    return image

按照位移移動(dòng)

print('第一步,點(diǎn)擊滑動(dòng)按鈕')
    ActionChains(driver).click_and_hold(on_element=element).perform()  # 點(diǎn)擊鼠標(biāo)左鍵,按住不放
    time.sleep(1)
    print('第二步,拖動(dòng)元素')
    for track in track_list:
         ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform() # 鼠標(biāo)移動(dòng)到距離當(dāng)前位置(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('第三步,釋放鼠標(biāo)')
    ActionChains(driver).release(on_element=element).perform()

詳細(xì)代碼

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))
    # 把無(wú)序的圖片 切成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):
    '''
    下載無(wú)序的圖片  然后進(jìn)行拼接 獲得完整的圖片
    :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) # 是一張無(wú)序的圖片
    image = merge_image(image_file,location_list)

    return image

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

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

    distance += 10  # 先滑過(guò)一點(diǎn),最后再反著滑動(dòng)回來(lái)
    # a = random.randint(1,3)
    while current < distance:
        if current < mid:
            # 加速度越小,單位時(shí)間的位移越小,模擬的軌跡就越多越詳細(xì)
            a = random.randint(2,4)  # 加速運(yùn)動(dòng)
        else:
            a = -random.randint(3,5) # 減速運(yùn)動(dòng)

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

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

    # 反著滑動(dòng)到大概準(zhǔn)確位置
    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):
    '''
      拿到滑動(dòng)驗(yàn)證碼需要移動(dòng)的距離
      :param image1:沒(méi)有缺口的圖片對(duì)象
      :param image2:帶缺口的圖片對(duì)象
      :return:需要移動(dòng)的距離
      '''
    # 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]) # 計(jì)算RGB差
            res_G = abs(pixel1[1] - pixel2[1])  # 計(jì)算RGB差
            res_B = abs(pixel1[2] - pixel2[2])  # 計(jì)算RGB差
            if res_R > threshold and res_G > threshold and res_B > threshold:
                return i  # 需要移動(dòng)的距離



def main_check_code(driver, element):
    """
     拖動(dòng)識(shí)別驗(yàn)證碼
    :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坐標(biāo)

    # 2 對(duì)比兩張圖片的所有RBG像素點(diǎn),得到不一樣像素點(diǎn)的x值,即要移動(dòng)的距離
    l = get_distance(image1, image2)
    print('l=',l)
    # 3 獲得移動(dòng)軌跡
    track_list = get_track(l)
    print('第一步,點(diǎn)擊滑動(dòng)按鈕')
    ActionChains(driver).click_and_hold(on_element=element).perform()  # 點(diǎn)擊鼠標(biāo)左鍵,按住不放
    time.sleep(1)
    print('第二步,拖動(dòng)元素')
    for track in track_list:
         ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform()  # 鼠標(biāo)移動(dòng)到距離當(dāng)前位置(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('第三步,釋放鼠標(biāo)')
    ActionChains(driver).release(on_element=element).perform()
    time.sleep(5)


def main_check_slider(driver):
    """
    檢查滑動(dòng)按鈕是否加載
    :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('超時(shí)錯(cuò)誤,繼續(xù)')
            time.sleep(5)


if __name__ == '__main__':
    try:
        count = 6  # 最多識(shí)別6次
        driver = webdriver.Chrome()
        # 等待滑動(dòng)按鈕加載完成
        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')
                # 得到成功標(biāo)志
                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('成功識(shí)別?。。。。?!')
                    count = 0
                    break
            except NoSuchElementException as e:
                print('識(shí)別錯(cuò)誤,繼續(xù)')
                count -= 1
                time.sleep(2)
        else:
            print('too many attempt check code ')
            exit('退出程序')
    finally:
        driver.close()

成功識(shí)別標(biāo)志css

滑動(dòng)成功標(biāo)志

以上就是Python破解滑動(dòng)驗(yàn)證碼的詳細(xì)內(nèi)容,更多Python自動(dòng)化測(cè)試的學(xué)習(xí)內(nèi)容請(qǐng)關(guān)注W3Cschool其它相關(guān)文章。

0 人點(diǎn)贊