一、滑动验证码
from selenium import webdriver
browser = webdriver.Chrome()
# 驱动Chrome浏览器打开滑动验证码示例页面
browser.get('http://www.porters.vip/captcha/sliders.html')
# 定位滑块
hover = browser.find_element_by_css_selector('.hover')
action = webdriver.ActionChains(browser)
action.click_and_hold(hover).perform() # 点击并保持不松开
action.move_by_offset(340, 0) # 设置滑动距离,横向距离340px,纵向距离0px
action.release().perform() # 松开鼠标
二、滑动拼图验证码
from selenium import webdriver
browser = webdriver.Chrome()
# 驱动Chrome浏览器打开滑动验证码示例页面
browser.get('http://www.porters.vip/captcha/jigsaw.html')
# 定位滑块
jigsawCircle = browser.find_element_by_css_selector('#jigsawCircle')
action = webdriver.ActionChains(browser)
# 点击并保持不松开
action.click_and_hold(jigsawCircle).perform()
# 返回当前页面的html代码
html = browser.page_source
import re
from parsel import Selector
sel = Selector(html)
# 获取圆角矩形和缺口的CSS样式
mbk_style = sel.css('#missblock::attr("style")').get()
tbk_style = sel.css('#targetblock::attr("style")').get()
# 编写用于从CSS样式中提取left属性值的匿名函数
extract = lambda x: ''.join(re.findall('left: (\d+|\d+.\d+)px', x))
# 调用匿名函数获取CSS样式中的left属性值
mbk_left = extract(mbk_style)
tbk_left = extract(tbk_style)
# 计算当前拼图验证码滑块所需移动的距离
distance = float(tbk_left) - float(mbk_left)
action.move_by_offset(distance, 0) # 设置滑动距离
action.release().perform() # 松开鼠标
三、滑动拼图验证码(Canvas)
from selenium import webdriver
browser = webdriver.Chrome()
# 驱动Chrome浏览器打开滑动验证码示例页面
browser.get('http://www.porters.vip/captcha/jigsawCanvas.html')
# 定位滑块
jigsawCircle = browser.find_element_by_css_selector('#jigsawCircle')
# 定位背景图片
jigsawCanvas = browser.find_element_by_css_selector('#jigsawCanvas')
jigsawCanvas.screenshot('before.png')
action = webdriver.ActionChains(browser)
# 点击并保持不松开
action.click_and_hold(jigsawCircle).perform()
# 执行js隐藏圆角矩形的HTML代码
scripts = """
var missblock = document.getElementById('missblock');
missblock.style['visibility'] = 'hidden';
"""
browser.execute_script(scripts)
# 再次截图
jigsawCanvas.screenshot('after.png')
from PIL import Image
# 打开待比对的图片
image_a = Image.open('after.png').convert('RGB')
image_b = Image.open('before.png').convert('RGB')
from PIL import ImageChops
# 使用ImageChops模块中的difference方法比对图片像素的不同
diff = ImageChops.difference(image_b, image_a)
# 获取图片差异位置的坐标
diff_position = diff.getbbox()
print(diff_position)
position_x = diff_position[0]
action.move_by_offset(int(position_x)-10, 0) # 设置移动距离
action.release().perform() # 松开鼠标