滑动验证码是本次项目目标网站的一个反扒策略,咱这小白借助selenium如何实现自动化破解滑动验证码。
之前的文章里写过selenium篇之滑动验证码使用PIL计算确缺口位置坐标的方式实现滑动验证码的破解,本次我们直接利用第三方来过滑动验证码,开发效率上会高很多。
![]()
前提准备
我们这里依然采用的是快识别,支持n多种验证码识别功能。
关于滑动验证码滑动轨迹,经过实测,目标网站反爬策略并没有那么严格,几乎只要不是一次滑动刚好对接就没问题。
代码正文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| class UnlockMixin: """验证码解锁"""
@staticmethod def base64_api(uname, pwd, img_base64, typeid): """ 获取验证码缺口 :param uname: 用户名 :param pwd: 密码 :param img_base64: selenium可直接拿到验证码base64 :param typeid: 33 :return:目标x轴坐标或错误信息 """ data = {"username": uname, "password": pwd, "typeid": typeid, "image": img_base64} url = "http://api.ttshitu.com/predict" result = json.loads(requests.post(url, json=data).text) if result['success']: return result["data"]["result"] else: return result["message"] return ""
def unlock(self): """解锁验证码""" if "请完成下列验证后继续" in self.driver.page_source: print("验证码出现了,快来解锁啊!") slide_img = self.driver.find_element_by_id("captcha-verify-image") btn = self.driver.find_element_by_xpath('//*[@id="secsdk-captcha-drag-wrapper"]/div[2]') screenshot_as_base64 = slide_img.screenshot_as_base64 slide_width = int( UnlockMixin.base64_api(uname='用户名', pwd='密码', img_base64=screenshot_as_base64, typeid=33)) time.sleep(5) tracks = UnlockMixin.get_track(slide_width - 6) ActionChains(self.driver).click_and_hold(btn).perform() time.sleep(0.15) for x in tracks: ActionChains(self.driver).move_by_offset(xoffset=x, yoffset=0).perform() ActionChains(self.driver).release(btn).perform() time.sleep(5)
@staticmethod def get_track(length): """生成滑动轨迹 滑动值拆分成和等于滑动值的数组 """ lis = [] x = random.randint(5, 10) while length - x >= 5: lis.append(x) length = length - x x = random.randint(5, 10) for i in range(length): lis.append(1) return lis if __name__ == '__main__': option = webdriver.ChromeOptions() option.add_experimental_option('excludeSwitches', ['enable-automation']) service = Service(r"chromedriver.exe") driver = webdriver.Chrome(service=service, options=option) driver.maximize_window() driver.get('https://www.douyin.com/video/7037691282721934599') time.sleep(random.random() * 5) un_handle = UnlockMixin() un_handle.unlock() time.sleep(1000)
|