QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

泡泡马甲APP 更多内容请下载泡泡马甲手机客户端APP 立即下载 ×
查看: 3293|回复: 0

[Python] 破解极验滑动验证码

[复制链接]

等级头衔

积分成就    金币 : 2802
   泡泡 : 1516
   精华 : 6
   在线时间 : 1242 小时
   最后登录 : 2024-4-18

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老

联系方式
发表于 2019-5-31 10:37:54 | 显示全部楼层 |阅读模式
1、极验滑动验证码原理6 B, e# e3 |2 G
11.png * b" m2 @2 Y. r
以上图片是最典型的要属于极验滑动认证了,极验官网:http://www.geetest.com/6 J: _9 h2 u. g9 j4 n5 ~3 S6 [
现在极验验证码已经更新到了 3.0 版本,截至 2017 年 7 月全球已有十六万家企业正在使用极验,每天服务响应超过四亿次,广泛应用于直播视频、金融服务、电子商务、游戏娱乐、政府企业等各大类型网站
8 y& [& x0 v& f- W) r对于这类验证,如果我们直接模拟表单请求,繁琐的认证参数与认证流程会让你蛋碎一地,我们可以用selenium驱动浏览器来解决这个问题,大致分为以下几个步骤:* Y: F) b! P9 U/ I
1、输入用户名,密码+ f6 B! q- M' B
2、点击按钮验证,弹出没有缺口的图
3 p4 C3 V1 H, s1 F; Z( Q3、获得没有缺口的图片) P+ J3 P5 B' x
4、点击滑动按钮,弹出有缺口的图
$ g8 v# @1 |2 F+ V5、获得有缺口的图片
: z' h9 {: c7 V+ q* `; |# k6、对比两张图片,找出缺口,即滑动的位移
9 l$ S  v7 z; M# R7、按照人的行为行为习惯,把总位移切成一段段小的位移
: K' j' _% L5 y& F8 D& p8、按照位移移动
. T4 b1 [$ F$ g  s9、完成登录
; _/ w# F# M- ~* `" h5 s& e, V/ A  x+ p6 `6 {6 v- @" w2 \
2、位移移动需要的基础知识
0 \; x4 n7 t1 Y" G$ e* q9 k: Y位移移动相当于匀变速直线运动,类似于小汽车从起点开始运行到终点的过程(首先为匀加速,然后再匀减速)。+ w) |* Y4 c1 V1 F% U
22.png
$ ^4 v0 a& f3 M& R其中a为加速度,且为恒量(即单位时间内的加速度是不变的),t为时间! h1 Q, T+ @2 X5 Z& n
33.png ! e5 u  V7 o. K: ?6 x% y
44.png ( a8 t4 i7 `3 |$ n- z* W
位移移动的代码实现
. f. ?7 t% @7 J$ _
  1. def get_track(distance):
  2.     '''
  3.     拿到移动轨迹,模仿人的滑动行为,先匀加速后匀减速
  4.     匀变速运动基本公式:
  5.     ①v=v0+at
  6.     ②s=v0t+(1/2)at²
  7.     ③v²-v0²=2as
  8.     :param distance: 需要移动的距离
  9.     :return: 存放每0.2秒移动的距离
  10.     '''
  11.     # 初速度
  12.     v=0
  13.     # 单位时间为0.2s来统计轨迹,轨迹即0.2内的位移
  14.     t=0.1
  15.     # 位移/轨迹列表,列表内的一个元素代表0.2s的位移
  16.     tracks=[]
  17.     # 当前的位移
  18.     current=0
  19.     # 到达mid值开始减速
  20.     mid=distance * 4/5
  21.     distance += 10  # 先滑过一点,最后再反着滑动回来
  22.     while current < distance:
  23.         if current < mid:
  24.             # 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细
  25.             a = 2  # 加速运动
  26.         else:
  27.             a = -3 # 减速运动
  28.         # 初速度
  29.         v0 = v
  30.         # 0.2秒时间内的位移
  31.         s = v0*t+0.5*a*(t**2)
  32.         # 当前的位置
  33.         current += s
  34.         # 添加到轨迹列表
  35.         tracks.append(round(s))
  36.         # 速度已经达到v,该速度作为下次的初速度
  37.         v= v0+a*t
  38.     # 反着滑动到大概准确位置
  39.     for i in range(3):
  40.        tracks.append(-2)
  41.     for i in range(4):
  42.        tracks.append(-1)
  43.     return tracks
对比两张图片,找出缺口; j7 n' x  T* \( e* g
  1. def get_distance(image1,image2):
  2.     '''
  3.       拿到滑动验证码需要移动的距离
  4.       :param image1:没有缺口的图片对象
  5.       :param image2:带缺口的图片对象
  6.       :return:需要移动的距离
  7.       '''
  8.     # print('size', image1.size)
  9.     threshold = 50
  10.     for i in range(0,image1.size[0]):  # 260
  11.         for j in range(0,image1.size[1]):  # 160
  12.             pixel1 = image1.getpixel((i,j))
  13.             pixel2 = image2.getpixel((i,j))
  14.             res_R = abs(pixel1[0]-pixel2[0]) # 计算RGB差
  15.             res_G = abs(pixel1[1] - pixel2[1])  # 计算RGB差
  16.             res_B = abs(pixel1[2] - pixel2[2])  # 计算RGB差
  17.             if res_R > threshold and res_G > threshold and res_B > threshold:
  18.                 return i  # 需要移动的距离
获得图片1 ~* T4 a! q; ?( M. H1 O
  1. def merge_image(image_file,location_list):
  2.     """
  3.      拼接图片
  4.     :param image_file:
  5.     :param location_list:
  6.     :return:
  7.     """
  8.     im = Image.open(image_file)
  9.     im.save('code.jpg')
  10.     new_im = Image.new('RGB',(260,116))
  11.     # 把无序的图片 切成52张小图片
  12.     im_list_upper = []
  13.     im_list_down = []
  14.     # print(location_list)
  15.     for location in location_list:
  16.         # print(location['y'])
  17.         if location['y'] == -58: # 上半边
  18.             im_list_upper.append(im.crop((abs(location['x']),58,abs(location['x'])+10,116)))
  19.         if location['y'] == 0:  # 下半边
  20.             im_list_down.append(im.crop((abs(location['x']),0,abs(location['x'])+10,58)))
  21.     x_offset = 0
  22.     for im in im_list_upper:
  23.         new_im.paste(im,(x_offset,0))  # 把小图片放到 新的空白图片上
  24.         x_offset += im.size[0]
  25.     x_offset = 0
  26.     for im in im_list_down:
  27.         new_im.paste(im,(x_offset,58))
  28.         x_offset += im.size[0]
  29.     new_im.show()
  30.     return new_im
  31. def get_image(driver,div_path):
  32.     '''
  33.     下载无序的图片  然后进行拼接 获得完整的图片
  34.     :param driver:
  35.     :param div_path:
  36.     :return:
  37.     '''
  38.     time.sleep(2)
  39.     background_images = driver.find_elements_by_xpath(div_path)
  40.     location_list = []
  41.     for background_image in background_images:
  42.         location = {}
  43.         result = re.findall('background-image: url\("(.*?)"\); background-position: (.*?)px (.*?)px;',background_image.get_attribute('style'))
  44.         # print(result)
  45.         location['x'] = int(result[0][1])
  46.         location['y'] = int(result[0][2])
  47.         image_url = result[0][0]
  48.         location_list.append(location)
  49.     print('==================================')
  50.     image_url = image_url.replace('webp','jpg')
  51.     # '替换url http://static.geetest.com/pictures/gt/579066de6/579066de6.webp'
  52.     image_result = requests.get(image_url).content
  53.     # with open('1.jpg','wb') as f:
  54.     #     f.write(image_result)
  55.     image_file = BytesIO(image_result) # 是一张无序的图片
  56.     image = merge_image(image_file,location_list)
  57.     return image
按照位移移动
% q$ ~, U7 q/ _! A( l, G) r
  1. print('第一步,点击滑动按钮')
  2.     ActionChains(driver).click_and_hold(on_element=element).perform()  # 点击鼠标左键,按住不放
  3.     time.sleep(1)
  4.     print('第二步,拖动元素')
  5.     for track in track_list:
  6.          ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform() # 鼠标移动到距离当前位置(x,y)
  7.     if l<100:
  8.         ActionChains(driver).move_by_offset(xoffset=-2, yoffset=0).perform()
  9.     else:
  10.         ActionChains(driver).move_by_offset(xoffset=-5, yoffset=0).perform()
  11.     time.sleep(1)
  12.     print('第三步,释放鼠标')
  13.     ActionChains(driver).release(on_element=element).perform()
详细代码
- @4 h1 f. S% H, w
  1. from selenium import webdriver
  2. from selenium.webdriver.support.ui import WebDriverWait # 等待元素加载的
  3. from selenium.webdriver.common.action_chains import ActionChains  #拖拽
  4. from selenium.webdriver.support import expected_conditions as EC
  5. from selenium.common.exceptions import TimeoutException, NoSuchElementException
  6. from selenium.webdriver.common.by import By
  7. from PIL import Image
  8. import requests
  9. import time
  10. import re
  11. import random
  12. from io import BytesIO
  13. def merge_image(image_file,location_list):
  14.     """
  15.      拼接图片
  16.     :param image_file:
  17.     :param location_list:
  18.     :return:
  19.     """
  20.     im = Image.open(image_file)
  21.     im.save('code.jpg')
  22.     new_im = Image.new('RGB',(260,116))
  23.     # 把无序的图片 切成52张小图片
  24.     im_list_upper = []
  25.     im_list_down = []
  26.     # print(location_list)
  27.     for location in location_list:
  28.         # print(location['y'])
  29.         if location['y'] == -58: # 上半边
  30.             im_list_upper.append(im.crop((abs(location['x']),58,abs(location['x'])+10,116)))
  31.         if location['y'] == 0:  # 下半边
  32.             im_list_down.append(im.crop((abs(location['x']),0,abs(location['x'])+10,58)))
  33.     x_offset = 0
  34.     for im in im_list_upper:
  35.         new_im.paste(im,(x_offset,0))  # 把小图片放到 新的空白图片上
  36.         x_offset += im.size[0]
  37.     x_offset = 0
  38.     for im in im_list_down:
  39.         new_im.paste(im,(x_offset,58))
  40.         x_offset += im.size[0]
  41.     new_im.show()
  42.     return new_im
  43. def get_image(driver,div_path):
  44.     '''
  45.     下载无序的图片  然后进行拼接 获得完整的图片
  46.     :param driver:
  47.     :param div_path:
  48.     :return:
  49.     '''
  50.     time.sleep(2)
  51.     background_images = driver.find_elements_by_xpath(div_path)
  52.     location_list = []
  53.     for background_image in background_images:
  54.         location = {}
  55.         result = re.findall('background-image: url\("(.*?)"\); background-position: (.*?)px (.*?)px;',background_image.get_attribute('style'))
  56.         # print(result)
  57.         location['x'] = int(result[0][1])
  58.         location['y'] = int(result[0][2])
  59.         image_url = result[0][0]
  60.         location_list.append(location)
  61.     print('==================================')
  62.     image_url = image_url.replace('webp','jpg')
  63.     # '替换url http://static.geetest.com/pictures/gt/579066de6/579066de6.webp'
  64.     image_result = requests.get(image_url).content
  65.     # with open('1.jpg','wb') as f:
  66.     #     f.write(image_result)
  67.     image_file = BytesIO(image_result) # 是一张无序的图片
  68.     image = merge_image(image_file,location_list)
  69.     return image
  70. def get_track(distance):
  71.     '''
  72.     拿到移动轨迹,模仿人的滑动行为,先匀加速后匀减速
  73.     匀变速运动基本公式:
  74.     ①v=v0+at
  75.     ②s=v0t+(1/2)at²
  76.     ③v²-v0²=2as
  77.     :param distance: 需要移动的距离
  78.     :return: 存放每0.2秒移动的距离
  79.     '''
  80.     # 初速度
  81.     v=0
  82.     # 单位时间为0.2s来统计轨迹,轨迹即0.2内的位移
  83.     t=0.2
  84.     # 位移/轨迹列表,列表内的一个元素代表0.2s的位移
  85.     tracks=[]
  86.     # 当前的位移
  87.     current=0
  88.     # 到达mid值开始减速
  89.     mid=distance * 7/8
  90.     distance += 10  # 先滑过一点,最后再反着滑动回来
  91.     # a = random.randint(1,3)
  92.     while current < distance:
  93.         if current < mid:
  94.             # 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细
  95.             a = random.randint(2,4)  # 加速运动
  96.         else:
  97.             a = -random.randint(3,5) # 减速运动
  98.         # 初速度
  99.         v0 = v
  100.         # 0.2秒时间内的位移
  101.         s = v0*t+0.5*a*(t**2)
  102.         # 当前的位置
  103.         current += s
  104.         # 添加到轨迹列表
  105.         tracks.append(round(s))
  106.         # 速度已经达到v,该速度作为下次的初速度
  107.         v= v0+a*t
  108.     # 反着滑动到大概准确位置
  109.     for i in range(4):
  110.        tracks.append(-random.randint(2,3))
  111.     for i in range(4):
  112.        tracks.append(-random.randint(1,3))
  113.     return tracks
  114. def get_distance(image1,image2):
  115.     '''
  116.       拿到滑动验证码需要移动的距离
  117.       :param image1:没有缺口的图片对象
  118.       :param image2:带缺口的图片对象
  119.       :return:需要移动的距离
  120.       '''
  121.     # print('size', image1.size)
  122.     threshold = 50
  123.     for i in range(0,image1.size[0]):  # 260
  124.         for j in range(0,image1.size[1]):  # 160
  125.             pixel1 = image1.getpixel((i,j))
  126.             pixel2 = image2.getpixel((i,j))
  127.             res_R = abs(pixel1[0]-pixel2[0]) # 计算RGB差
  128.             res_G = abs(pixel1[1] - pixel2[1])  # 计算RGB差
  129.             res_B = abs(pixel1[2] - pixel2[2])  # 计算RGB差
  130.             if res_R > threshold and res_G > threshold and res_B > threshold:
  131.                 return i  # 需要移动的距离
  132. def main_check_code(driver, element):
  133.     """
  134.      拖动识别验证码
  135.     :param driver:
  136.     :param element:
  137.     :return:
  138.     """
  139.     image1 = get_image(driver, '//div[@class="gt_cut_bg gt_show"]/div')
  140.     image2 = get_image(driver, '//div[@class="gt_cut_fullbg gt_show"]/div')
  141.     # 图片上 缺口的位置的x坐标
  142.     # 2 对比两张图片的所有RBG像素点,得到不一样像素点的x值,即要移动的距离
  143.     l = get_distance(image1, image2)
  144.     print('l=',l)
  145.     # 3 获得移动轨迹
  146.     track_list = get_track(l)
  147.     print('第一步,点击滑动按钮')
  148.     ActionChains(driver).click_and_hold(on_element=element).perform()  # 点击鼠标左键,按住不放
  149.     time.sleep(1)
  150.     print('第二步,拖动元素')
  151.     for track in track_list:
  152.          ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform()  # 鼠标移动到距离当前位置(x,y)
  153.      time.sleep(0.002)
  154.     # if l>100:
  155.     ActionChains(driver).move_by_offset(xoffset=-random.randint(2,5), yoffset=0).perform()
  156.     time.sleep(1)
  157.     print('第三步,释放鼠标')
  158.     ActionChains(driver).release(on_element=element).perform()
  159.     time.sleep(5)
  160. def main_check_slider(driver):
  161.     """
  162.     检查滑动按钮是否加载
  163.     :param driver:
  164.     :return:
  165.     """
  166.     while True:
  167.         try :
  168.             driver.get('http://www.cnbaowen.net/api/geetest/')
  169.             element = WebDriverWait(driver, 30, 0.5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'gt_slider_knob')))
  170.             if element:
  171.                 return element
  172.         except TimeoutException as e:
  173.             print('超时错误,继续')
  174.             time.sleep(5)
  175. if __name__ == '__main__':
  176.     try:
  177.         count = 6  # 最多识别6次
  178.         driver = webdriver.Chrome()
  179.         # 等待滑动按钮加载完成
  180.         element = main_check_slider(driver)
  181.         while count > 0:
  182.             main_check_code(driver,element)
  183.             time.sleep(2)
  184.             try:
  185.                 success_element = (By.CSS_SELECTOR, '.gt_holder .gt_ajax_tip.gt_success')
  186.                 # 得到成功标志
  187.                 print('suc=',driver.find_element_by_css_selector('.gt_holder .gt_ajax_tip.gt_success'))
  188.                 success_images = WebDriverWait(driver, 20).until(EC.presence_of_element_located(success_element))
  189.                 if success_images:
  190.                     print('成功识别!!!!!!')
  191.                     count = 0
  192.                     break
  193.             except NoSuchElementException as e:
  194.                 print('识别错误,继续')
  195.                 count -= 1
  196.                 time.sleep(2)
  197.         else:
  198.             print('too many attempt check code ')
  199.             exit('退出程序')
  200.     finally:
  201.         driver.close()
成功识别标志css8 v$ S5 W% R: K- ?% |# T* x
55.png

+ Z2 P" ?/ P5 n3 b% R9 Q, n- H
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号 )

GMT+8, 2024-4-26 21:21

Powered by paopaomj X3.4 © 2016-2024 sitemap

快速回复 返回顶部 返回列表