影刀RPA 验证码处理方案:识别与绕过策略

影刀RPA 验证码处理方案:识别与绕过策略 影刀RPA 验证码处理方案识别与绕过策略署名林焱什么情况用什么做网页自动化采集时登录或频繁请求经常遇到验证码。验证码类型不同处理策略也不同。验证码类型推荐方案成功率纯数字/字母图片OCR识别 / 打码平台80-95%滑动拼图模拟轨迹滑动70-90%点选文字/图标打码平台 / AI模型60-85%reCAPTCHA/极验Cookie保持 降低频率视情况怎么做方案一影刀OCR识别简单验证码对于简单的数字字母验证码纯文本、无干扰线流程设计 1. 【等待元素出现】验证码图片元素 2. 【截图】截取验证码区域 3. 【OCR识别】识别截图中的文字 4. 【设置变量】识别结果存入变量 5. 【填写输入框】把识别结果填入验证码输入框 6. 【点击】点击登录按钮Python代码块优化识别拼多多店群自动化报活动上架fromPILimportImage,ImageEnhance,ImageFilterimportos# 验证码图片预处理提升OCR识别率defpreprocess_captcha(img_path,output_path):imgImage.open(img_path)# 转灰度imgimg.convert(L)# 二值化threshold160低于160变黑高于变白threshold160table[]foriinrange(256):ifithreshold:table.append(0)else:table.append(1)imgimg.point(table,1)# 去噪中值滤波imgimg.filter(ImageFilter.MedianFilter(size3))# 放大2倍提高OCR对小字识别率imgimg.resize((img.width*2,img.height*2))img.save(output_path)returnoutput_path# 预处理后交给影刀OCR指令识别preprocess_captcha(rD:\temp\验证码.png,rD:\temp\验证码_处理后.png)方案二滑动验证码处理importrandomimporttimedefgenerate_slide_track(distance,duration_ms800): 生成滑动轨迹模拟人工滑动先快后慢 distance: 需要滑动的距离像素 duration_ms: 总时长毫秒 track[]current0# 减速阶段参数middistance*0.7# 前70%加速后30%减速steps30# 总步数intervalduration_ms/stepsforiinrange(steps):ifcurrentmid:# 加速阶段ti/steps moveint(distance*0.7*(2*t-t*t))else:# 减速阶段remainingdistance-current movemax(1,int(remaining*0.15))# 添加随机抖动jitterrandom.randint(-1,2)movemax(1,movejitter)currentmove track.append({x:min(current,distance),y:random.randint(-1,1),# y方向微小抖动delay:intervalrandom.uniform(-5,10)})# 最后精确到目标位置track.append({x:distance,y:0,delay:100})# 稍微过冲再回退模拟人工微调track.append({x:distance3,y:0,delay:50})track.append({x:distance,y:0,delay:80})returntrack# 生成滑动轨迹trackgenerate_slide_track(200)# 滑动200像素# 在影刀中用【模拟鼠标拖动】按轨迹滑动# yd_output {track: track}影刀流程配合1. 【等待元素出现】滑块元素 2. 【执行Python代码】生成滑动轨迹 3. 【鼠标按下】在滑块上按下 4. 循环按轨迹移动鼠标 - 【设置变量】x坐标、y坐标、延迟时间 - 【鼠标移动】到相对位置 - ![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/6dceb5cdbd3446a8948073d94dd417ea.png#pic_center) - 【等待】延迟时间 5. 【鼠标释放】松开滑块 6. 【等待】检测是否验证成功方案三打码平台API调用importrequestsimportbase64importtimedefrecognize_captcha(image_path,api_url,api_key):调用打码平台识别验证码# 读取图片并base64编码withopen(image_path,rb)asf:img_base64base64.b64encode(f.read()).decode()# 提交识别任务responserequests.post(api_url,json{image:img_base64,type:captcha,# 验证码类型api_key:api_key},timeout30)resultresponse.json()ifresult.get(code)0:returnresult.get(data,{}).get(result,)else:print(f识别失败:{result.get(message)})returnNone# 使用coderecognize_captcha(rD:\temp\验证码.png,https://api.example.com/recognize,your_api_key)ifcode:print(f验证码:{code})方案四Cookie保持避免频繁触发验证码importrequestsimportpickleimportosclassCookieManager:保持登录状态避免频繁触发验证码def__init__(self,cookie_filecookies.pkl):self.cookie_filecookie_file self.sessionrequests.Session()self.session.headers.update({User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36})defsave_cookies(self):保存Cookie到文件withopen(self.cookie_file,wb)asf:pickle.dump(self.session.cookies,f)defload_cookies(self):加载已保存的Cookieifos.path.exists(self.cookie_file):withopen(self.cookie_file,rb)asf:self.session.cookiespickle.load(f)returnTruereturnFalsedefis_logged_in(self,check_url):检查Cookie是否还有效respself.session.get(check_url,allow_redirectsFalse)returnresp.status_code200defrequest_with_retry(self,url,methodGET,max_retries3,**kwargs):带重试的请求forattemptinrange(max_retries):try:respself.session.request(method,url,timeout15,**kwargs)if验证码inresp.textorcaptchainresp.text.lower():print(f触发验证码尝试{attempt1}/{max_retries})time.sleep(5*(attempt1))# 等待后重试continuereturnrespexceptExceptionase:print(f请求失败:{e}, 重试{attempt1})time.sleep(3)returnNone# 使用cmCookieManager(rD:\config\site_cookies.pkl)cm.load_cookies()# 每次请求用session保持Cookierespcm.request_with_retry(https://example.com/data)完整流程带验证码处理的登录importrequestsimporttimeimportos# yd_input: username, password, max_captcha_retriesusernameyd_input.get(username,)passwordyd_input.get(password,)max_retriesyd_input.get(max_captcha_retries,3)sessionrequests.Session()session.headers.update({User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36})# 先访问登录页获取Cookiesession.get(https://example.com/login)forattemptinrange(max_retries):print(f第{attempt1}次尝试登录)# 1. 下载验证码图片captcha_respsession.get(https://example.com/captcha.png,timeout10)captcha_pathrD:\temp\captcha.pngwithopen(captcha_path,wb)asf:f.write(captcha_resp.content)# 2. 识别验证码这里用影刀OCR或打码平台# 实际使用时用影刀OCR指令识别或调用打码API# captcha_code yd_input.get(captcha_code, ) # 从影刀获取# 模拟OCR结果captcha_code# 实际从OCR获取ifnotcaptcha_code:print(验证码识别失败重试)time.sleep(2)continue# 3. 提交登录login_data{username:username,password:password,captcha:captcha_code}respsession.post(https://example.com/login,datalogin_data,timeout15)# 4. 检查是否登录成功if登录成功inresp.textorresp.urlhttps://example.com/home:# 保存Cookie供后续使用importpicklewithopen(rD:\config\cookies.pkl,wb)asf:pickle.dump(session.cookies,f)yd_output{status:ok,message:登录成功,attempts:attempt1}breakelif验证码inresp.text:print(验证码错误重试)time.sleep(2)else:print(f登录失败:{resp.text[:200]})yd_output{status:error,message:登录失败}breakelse:yd_output{status:error,message:f超过最大重试次数{max_retries}}有什么坑坑一OCR识别率太低现象简单数字验证码OCR识别率只有30%。原因验证码有干扰线、背景噪点、字体扭曲等干扰。解决图片预处理 多次重试fromPILimportImage,ImageFilterdefenhance_captcha(img_path):验证码图片预处理imgImage.open(img_path)# 1. 转灰度imgimg.convert(L)# 2. 增强对比度fromPILimportImageEnhance enhancerImageEnhance.Contrast(img)imgenhancer.enhance(2.0)# 3. 二值化imgimg.point(lambdax:0ifx140else255,1)# 4. 去噪imgimg.filter(ImageFilter.MedianFilter(size3))# 5. 放大imgimg.resize((img.width*3,img.height*3))img.save(img_path)returnimg_path# 预处理后识别率可提升到60-80%# 配合多次重试识别3次取出现最多的结果坑二滑动验证码总被识别为机器现象滑动距离对了但验证不通过提示请在滑块上拖动。TEMU店群矩阵自动化运营核价报活动原因滑动轨迹太规整——匀速直线移动没有人类滑动的特征先快后慢、微小抖动。解决使用更真实的轨迹模拟# 关键人类滑动有三个特征# 1. 先加速后减速不是匀速# 2. y方向有微小波动# 3. 结尾有过冲和回退# 参考前面的 generate_slide_track 函数# 核心是 mid点之前用加速公式之后用减速公式# 最后加过冲回退坑三验证码图片每次请求都变现象下载了验证码图片识别后提交但系统说验证码不对。原因验证码图片和登录请求不在同一个Session中服务器生成了新的验证码。解决用同一个requests.Session# 正确用同一个sessionsessionrequests.Session()# 下载验证码服务器记住了这个验证码的值captcha_respsession.get(https://example.com/captcha.png)# 提交登录同一个sessionCookie一致login_respsession.post(https://example.com/login,data{...})# 错误两个独立请求# captcha requests.get(https://example.com/captcha.png) ❌ 新Session# login requests.post(https://example.com/login, data{...}) ❌ 新Session验证码对不上坑四频繁触发验证码导致IP被封现象连续识别验证码登录多次后IP被封禁。原因短时间内大量请求触发了反爬机制。解决控制频率 Cookie复用importtimeimportrandom# 1. 成功登录后保存Cookie后续请求不再登录# 2. 请求间隔加随机延迟defsmart_sleep(min_sec2,max_sec5):随机延迟避免规律性time.sleep(random.uniform(min_sec,max_sec))# 3. 设置合理的重试间隔forattemptinrange(max_retries):# 尝试操作ifsuccess:break# 失败后指数退避wait_time(2**attempt)random.uniform(0,3)print(f等待{wait_time:.1f}秒后重试)time.sleep(wait_time)