Python爬虫滑块验证

滑块验证网址:http://www.cnbaowen.net/api/geetest/

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
import osdef merge_image(image_file,location_list):"""拼接图片:param image_file::param location_list::return:"""im = Image.open(image_file) #打开图片二进制文件im.save('code.jpg') #保存到code.jpgnew_im = Image.new('RGB',(260,116)) #空白图片长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.crop(图片的x左坐标,图片的y上坐标,图片的x右坐标,图片的y下坐标)左、上、右和下像素的4元组im_list_upper.append(im.crop((abs(location['x']),58,abs(location['x'])+10,116)))if location['y'] == 0:  # 下半边#同理如上,返回一个对象的对象PIL.Image.Image的objectim_list_down.append(im.crop((abs(location['x']),0,abs(location['x'])+10,58)))x_offset = 0for im in im_list_upper: #拼接上半部分new_im.paste(im,(x_offset,0))  # 把小图片放到 新的空白图片上,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 = []image_url=""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])   #获取无序图片x坐标location['y'] = int(result[0][2])  #获取无序图片y坐标image_url = result[0][0].replace('webp','jpg')     #图片链接location_list.append(location)  #将xy坐标 字典放入列表中 {"x":"-157","y":"-58"}print('==================================')# '替换url http://static.geetest.com/pictures/gt/579066de6/579066de6.webp'#content响应的内容,以字节为单位image_result = requests.get(image_url).content  #b'\xff\ 字节#BytesIO相当于实现一个with open:# with open('1.jpg','wb') as f:#     f.write(image_result)image_file = BytesIO(image_result) # 是一张无序的图片 返回一个对象<_io.BytesIO object at 0x000001B5A139D3B8>image = merge_image(image_file,location_list) #拼接图片 <PIL.Image.Image image mode=RGB size=260x116 at 0x1B5A131AD30>return imagedef 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.2# 位移/轨迹列表,列表内的一个元素代表0.2s的位移tracks=[]# 当前的位移current=0accuracy_distance=distance# 到达目标值的八分之七,开始减速mid=distance * 3/5# distance += 20 # 先滑过一点,最后再反着滑动回来# a = random.randint(1,3)while current < distance:if current < mid:# 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细a = random.randint(2,4) # 加速运动的加速度else:a = -random.randint(2,4) # 减速运动的加速度# 初速度v0 = v# 0.2秒时间内的位移s = v0*t+0.5*a*(t**2)  #s=v0t+(1/2)at²# 当前的位置current += s# 添加到轨迹列表print(a)tracks.append(round(s)) #添加每一次x位置的坐标# 速度已经达到v,该速度作为下次的初速度v= v0+a*t       #记录每一次0.2s的末速度,作为下一个0.2s的初速度,拼接一个滑动动作# 反着滑动到大概准确位置if abs(current - distance) > 1:s = -(current - distance - 1)tracks.append(round(s))  # 添加每一次x位置的坐标print(current,"<><><>",distance)# 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 #设置rgb差值for i in range(0,image1.size[0]):  # 0到260的x坐标 0for j in range(0,image1.size[1]):  # 0到160的y坐标0pixel1 = image1.getpixel((i,j)) #返回一个像素值的元组 <class 'tuple'>: (255, 101, 86)pixel2 = image2.getpixel((i,j)) #<class 'tuple'>: (255, 101, 86)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:#即判断两张图片的每个像素的色差大于五十,即锁定了缺口,#因为滑块起点始终为0,i 的坐标,即为滑块x轴移动距离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') #拼接无序缺口图片1image2 = get_image(driver, '//div[@class="gt_cut_fullbg gt_show"]/div') # 拼接无序完整图片2# 图片上 缺口的位置的x坐标# 2 对比两张图片的所有RBG像素点,得到不一样像素点的x值,即要移动的距离l = get_distance(image1, image2) #像素值 182print('l=',l)# 3 获得移动轨迹track_list = get_track(l) #模拟人行为滑动,即匀加速在匀速print('第一步,点击滑动按钮')#ActionChains执行用户操作的WebDriver实例,按住元素上的鼠标左键。on_element:鼠标向下移动的元素。perform() 执行操作ActionChains(driver).click_and_hold(on_element=element).perform()  # 点击鼠标左键,按住不放time.sleep(0.3)print('第二步,拖动元素')for track in track_list:#move_by_offset将鼠标移动到当前鼠标位置的偏移量。xoffset为x轴,yoffset为y轴ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform()  # 鼠标移动到距离当前位置(x,y)time.sleep(0.003)# if l>100:ActionChains(driver).move_by_offset(xoffset=-random.randint(2,5), yoffset=0).perform()time.sleep(0.3)print('第三步,释放鼠标')#释放元素上的已按住的鼠标按钮。 on_element:鼠标向上移动的元素。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 elementexcept TimeoutException as e:print('超时错误,继续')time.sleep(5)if __name__ == '__main__':count = 6  # 最多识别6次chrome_path = os.path.join(os.path.dirname(__file__), "chromedriver.exe")  # 拼接chrome路径driver = webdriver.Chrome(executable_path=chrome_path)  # 示列化Chrometry:# 等待滑动按钮加载完成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'))#等待20s,直到找到成功标签success_images = WebDriverWait(driver, 20).until(EC.presence_of_element_located(success_element))if success_images: #存在,不为空print('成功识别!!!!!!')count = 0#这里验证完成后就自动跳转,或者再加一个点击跳转,后面跟上你的爬虫数据爬取的自定义函数模块,进行解析即可breakexcept NoSuchElementException as e:print('识别错误,继续')count -= 1time.sleep(2)else:print('too many attempt check code ')exit('退出程序')finally:driver.close()

参考:https://www.cnblogs.com/xiao-apple36/p/8878960.html

Python爬虫滑块验证相关推荐

  1. python爬虫滑块验证怎么解决

    对于 Python 爬虫中遇到的滑块验证,你可以考虑以下几种方法来解决: 手动解决滑块验证:在爬虫程序中手动解决滑块验证,比如通过手动模拟鼠标滑动操作来完成滑块验证. 使用浏览器插件解决滑块验证:你可 ...

  2. python实现滑块验证功能_python3.8.1+selenium实现登录滑块验证功能

    python3.8.1+selenium解决登录滑块验证的问题,先给大家分享一个效果图,感觉不错,可以参考实现代码. 这里的滑块是qq邮箱的截图,如图所示,可以作为同类滑块验证的参考. "& ...

  3. python实现滑块验证功能_Python 滑块验证码

    image 看了滑块验证码(滑动验证码)相比图形验证码,破解难度如何?中<Python3网络爬虫开发实战>作者 崔庆才丨静觅 的一个回答,里面有详细介绍如何对抗滑块验证码,因此学习一下,对 ...

  4. Python解决滑块验证,Scarpy框架采集数据到redis数据库!

    目录 架构介绍 安装创建和启动 配置文件目录介绍 爬取数据,并解析 数据持久化 保存到文件 保存到redis 动作链,控制滑动的验证码 架构介绍 Scrapy一个开源和协作的框架,其最初是为了页面抓取 ...

  5. Python selenium 滑块验证--分析与实现

    本文仅供学习交流使用,如侵立删! 滑动模块 from selenium import webdriver from selenium.webdriver.common.by import By fro ...

  6. 凡科网JS逆向后跳出的滑块验证(base64图片解码之后的破解滑块验证)

    目录 1.前提和大概思路概述 2. 转换思路selenium和验证滑块图片的获取处理 3.总结 1.前提和大概思路概述 只是学习的途中有一些新的发现,分享给大家,希望对你们有帮助. 凡科网的JS逆向的 ...

  7. python网络爬虫抹除webdriver指纹绕过淘宝滑块验证登录

    对于爬虫工程师,最常遇到的需求就是抓取电商网站的数据,那么电商数据最受哪些公司平台的注意呢?以下是几个例子 广告商:广告商透过爬虫定期抓取你店铺的数据,并对店铺包括销量,热度,好评,新上线产品好评度, ...

  8. Python爬虫拓展应用:最新版本问卷星自动刷,包括解决智能验证、滑块等问题

    Python爬虫拓展应用: 最新版本问卷星自动刷,包括:解决智能验证.滑块等问题 Python爬虫自动刷"问卷星"网站问卷 爬虫运行准备 爬虫运行代码 代码解释 参考博客 Pyth ...

  9. python 淘宝滑块验证_selenium 反爬虫之跳过淘宝滑块验证!首先要搞定JS!

    在处理问题的之前,给大家个第一个锦囊! 你需要将chorme更新到最新版版本84,下载对应的chorme驱动 注意 划重点!!一定要做这一步,因为我用的83的chorme他是不行滴,~~~~~~~ 问 ...

  10. python五行代码解决滑块验证的缺口距离识别,破解滑块验证...

    目前网上关于滑块的缺口识别的方法很多,但是都不极简,看起来繁杂,各种算法的都有,有遍历的有二分法的,今天写个最简单,准确率最高的. 直接看代码: def FindPic(target, templat ...

最新文章

  1. 手机拍照软件for android1.6,RookieCam
  2. hive同时不包含一些字符串_Hive中常用的字符串操作
  3. 实战 Deep Insert (SAP OData Service 实战系列)
  4. AAAI2021论文合集汇总!(持续更新)
  5. python查看opencv版本命令行_查看python下OpenCV版本的方法
  6. 运行时数据区(Run-Time Data Areas)
  7. 执行力:Just Do It
  8. 烽火2640路由器命令行手册-12-IBM网络配置命令
  9. 无连接可靠传输_这些RF连接器设计原则你应该多了解一下
  10. 智取风控特征—巧用PBOC落地额度模型
  11. php 数组 true,php – 对于不存在的数组键,isset()返回true的奇怪行为
  12. python 选择多个文件_python-PyQt QFileDialog-多目录选择
  13. 在线预览PDF(pdfobject)
  14. GalForUnity简介
  15. matlab定积分矩形法实验报告,矩形法求定积分
  16. Android源码分析(十三)----SystemUI下拉状态栏如何添加快捷开关
  17. vue使用百度地图 图标自定义 之 本地图标显示问题
  18. Foo,getName题解分析
  19. 健康知识竞答线上活动方案——微信答题小程序实现
  20. linux tuxedo查看服务进程数,tuxedo管理命令之tmboot与tmshutdown

热门文章

  1. photoshop 插件_Photoshop的光度模式
  2. matlab进行mppt控制仿真,光伏发电系统MPPT控制仿真模型
  3. yum install gcc 下载失败有可能是这个原因?
  4. 注册表修改系统分辨率
  5. 数据挖掘基础知识点总结
  6. 【总结】编程语言的分类
  7. AutoCAD Plant 3d管道设计基础到中高级进阶视频教程
  8. eclipse 使用教程
  9. 【ES实战】ES-Hadoop中的配置项说明
  10. ios 更多 Url Schemes