代码拉取完成,页面将自动刷新
from selenium_base import *
from PIL import Image, ImageChops
import random
url = 'http://127.0.0.1:8888/captcha_slide_puzzle_canvas_mousemove'
before = 'before.png'
after = 'after.png'
def get_track(distance):
"""
生成一个轨迹来模拟用户的
:param distance: 需移动距离
:return:
"""
# 移动轨迹
track = []
# 当前位移
current = 0
# 减速阈值
mid = distance * 4 / 5
# 计算间隔
t = 0.2
# 初速度
v = 1
while current < distance:
# 先快后慢
if current < mid:
a = 4
else:
a = -3
v0 = v
# 当前速度
v = v0 + a * t
# 移动距离
move = v0 * t + 1 / 2 * a * t * t
# 当前位移
current += move
# 加入轨迹
track.append(round(move))
return track
def get_diff_position(before, after):
before_img = Image.open(before)
after_img = Image.open(after)
# PNG文件是PngImageFile对象,与RGBA模式
# ImageChops.difference方法只能对比RGB模式,所以需要转换一下格式
before_img = before_img.convert('RGB')
after_img = after_img.convert('RGB')
# 对比2张图片中像素不同的位置
diff = ImageChops.difference(before_img, after_img)
# 获取图片差异位置坐标
# 坐标顺序为左、上、右、下
diff_position = diff.getbbox()
position_x = diff_position[0]
return position_x
try:
brower = get_brower()
brower.get(url)
brower.add_cookie({"name": "session",
"value": ".eJyrViotTi1SsqpWyiyOT0zJzcxTsjLQUcrJTwexSopKU3WUcvOTMnNSlayUDM3gQEkHrDE-M0XJyhjCzkvMBSmKKTVNMjMDkiamFkq1tQDfeR3n.YLOC4w.Xbnx1QbrvUh8OUPb5jauC_Aau9U"})
brower.get(url)
# 定位到canvas
jigsawCanvas = brower.find_element_by_id('jigsawCanvas')
# 保存背景图
jigsawCanvas.screenshot(before)
action = webdriver.ActionChains(brower)
jigsawCircle = brower.find_element_by_id('jigsawCircle')
# 显示目标缺口
action.click_and_hold(jigsawCircle).move_by_offset(1, 0).release().perform()
# 执行script,隐藏拖动滑块
script = """
var cralwer_missblock = document.getElementById('missblock');
cralwer_missblock.style['visibility'] = 'hidden';
"""
brower.execute_script(script)
jigsawCanvas.screenshot(after)
offset_x = get_diff_position(before, after)
# 执行script,显示拖动滑块,方便我判断移动距离
script = """
var cralwer_missblock = document.getElementById('missblock');
cralwer_missblock.style['visibility'] = 'visible';
"""
brower.execute_script(script)
# 移动滑块
# 保存图片的宽度与Canvas显示的宽度,差2倍(这是我4k屏幕导致的)
action.release().perform()
offset_x = (offset_x / 2) - 10
# 先快后慢
tracks = get_track(offset_x)
action.click_and_hold(jigsawCircle)
i = 1
for x in tracks:
# 模拟抖动
if random.random() - 0.5 > 0:
offset_y = random.random() * 10 / 2
if random.random() - 0.5 > 0:
offset_y = -offset_y
else:
offset_y = 0
action.move_by_offset(x, offset_y)
i = i + 1
time.sleep(0.5)
action.release().perform()
finally:
time.sleep(5)
brower.close()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。