import random
import ddddocr
from playwright.sync_api import sync_playwright
import time
import requests
with sync_playwright() as p:
det = ddddocr.DdddOcr(det=False, ocr=False)
browser = p.chromium.launch(headless=False, args=[
'--disable-blink-features=AutomationControlled',
'--disable-infobars',
'--disable-web-security',
'--disable-features=IsolateOrigins,site-per-process'
])
context = browser.new_context(
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
viewport={'width': 1280, 'height': 800}
)
page = context.new_page()
# 打开网页
page.goto("https://www.zhihu.com/")
# 找到手机输入位置并输入手机号
page.fill('//*[@name="username"]', "18888888888")
time.sleep(1)
# 找到按钮并点击
page.click('//*[contains(@class, "CountingDownButton")]')
# 等待弹窗出现
time.sleep(3)
# 获取滑块和背景图片的元素
bg_img_src = page.get_attribute('//*[@class="yidun_bg-img"]', "src")
jigsaw_img_src = page.get_attribute('//*[@class="yidun_jigsaw"]', "src")
# 下载图片
bg_img_data = requests.get(bg_img_src).content
jigsaw_img_data = requests.get(jigsaw_img_src).content
with open("full.jpg", "wb") as f:
f.write(bg_img_data)
with open("part.png", "wb") as f:
f.write(jigsaw_img_data)
# 重新读取图片并计算滑块需要移动的距离
with open("part.png", "rb") as f:
target_bytes = f.read()
with open("full.jpg", "rb") as f:
background_bytes = f.read()
res = det.slide_match(target_bytes, background_bytes)
distance = res["target"][0] + 8
print(f"滑块需要移动的距离为 {distance} 像素。")
# 找到滑块并模拟拖动
slider = page.locator('//*[@class="yidun_slider__icon"]')
box = slider.bounding_box()
# 计算滑动轨迹
def human_like_track(distance):
track = []
current = 0
mid = distance * 3 / 4
t = 0.2
v = 0
while current < distance:
if current < mid:
a = random.uniform(2, 3)
else:
a = -random.uniform(2, 4)
v0 = v
v = v0 + a * t
move = v0 * t + 0.5 * a * (t ** 2)
current += move
track.append(round(move))
# 模拟拉扯动作
over_shoot = random.randint(10, 15) # 过头的距离稍微大一点
track.append(over_shoot)
track.append(-over_shoot + random.randint(1, 3))
return track
track = human_like_track(distance)
# 模拟拖动滑块
page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
page.mouse.down()
current_x = box["x"] + box["width"] / 2
for move in track:
current_x += move
page.mouse.move(current_x, box["y"] + box["height"] / 2)
if move < 0: # 拉回来的时候速度稍微慢一点
time.sleep(random.uniform(0.05, 0.1))
else: # 往左的时候速度稍微快一点
time.sleep(random.uniform(0.01, 0.02))
page.mouse.up()
time.sleep(20)
# 关闭浏览器
browser.close()
标签:box,random,img,示例,track,move,极验,v3,page
From: https://www.cnblogs.com/miaokela/p/18518330