python selenium 滑块验证码处理

# coding=utf-8


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 selenium.webdriver.chrome.options import Options

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('template.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)at²

    ③v²-v0²=2as


    :param distance: 需要移动的距离

    :return: 存放每0.2秒移动的距离

    '''

    # 初速度

    v=0

    # 单位时间为0.2s来统计轨迹,轨迹即0.2内的位移

    t=0.1

    # 位移/轨迹列表,列表内的一个元素代表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(1,3) # 加速运动

        else:

            a = -random.randint(3,5) # 减速运动


        # 初速度

        v0 = v

        # 0.2秒时间内的位移

        s = v0*t+0.5*a*(t**2)

        # 当前的位置

        current += s

        # 添加到轨迹列表

        tracks.append(round(s))


        # 速度已经达到v,该速度作为下次的初速度

        v= v0+a*t


    # 反着滑动到大概准确位置

    for i in range(2):

       tracks.append(-random.randint(2,3))

    for i in range(2):

       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.001)

    # if l>100:

    ActionChains(driver).move_by_offset(xoffset=-random.randint(2,5), yoffset=0).perform()

    time.sleep(2)

    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('超时错误,继续')

            time.sleep(5)



if __name__ == '__main__':

    try:

        count = 6 # 最多识别6次

        options = Options()

        options.add_experimental_option('useAutomationExtension', False)

        options.add_experimental_option('excludeSwitches', ['enable-automation'])

        driver = webdriver.Chrome(options=options)

        # driver = webdriver.Chrome()

        driver.maximize_window()

        # 等待滑动按钮加载完成

        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('成功识别!!!!!!')

                    time.sleep(3)

                    count = 0

                    break

            except NoSuchElementException as e:

                print('识别错误,继续')

                count -= 1

                time.sleep(2)

        else:

            print('too many attempt check code ')

            exit('退出程序')

    finally:

        driver.close()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容