2 Star 5 Fork 14

ayuliao/AntiCrawlers

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
案例27-鼠标轨迹检测反爬.py 3.30 KB
一键复制 编辑 原始数据 按行查看 历史
二两的分身 提交于 2021-07-04 22:59 . enjoy code
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()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ayuLiao/anti-crawlers.git
git@gitee.com:ayuLiao/anti-crawlers.git
ayuLiao
anti-crawlers
AntiCrawlers
master

搜索帮助