selenium破解中文验证码

今日在做一个与爬虫相关的项目,奈何自己是爬虫菜鸟,于是走捷径想用selenium去爬取目标去网站,奈何目标很强大,某音短视频,网页反爬策略也是很多,后面我这里会一一列出。

验证码如图所示:

其实这个验证码日常还是很常见的,但是实际操作发现,想找一个同样的验证码去测试破解还是很困难的。如果你想着直接在某音短视频直接破解你会发现怎么都触发不了这个验证码的出现,反倒是挂到服务器爬取的时候,经常会卡死到验证码这里。

后来实测发现触发该验证码并不是时间久才能触发的,当弹出滑动验证码时下拉滚动条,原来的滑动验证码就会变成上图中的中文验证码,如此便方便我们测试破解它了。关于滑动验证码的破解要参考我另外一篇文章**selenium篇之滑动验证码**了。

破解前的准备

  • 人工智能机器学习相关知识库

  • 第三方验证识别平台(我这里使用的是快识别)

第一种方法**selenium篇之滑动验证码**中提到过,相对来说有一定的学习成本,方式二真的适合快速开发,价格也不贵,所以本文直接采用第二种方式。

代码正文

为了方便,我这里代码稍微有点乱,大家自己项目里整合下即可:

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
# @Time    : 2022/1/4 9:50
# @Author : 托小尼
# @Email : 646547989@qq.com
# @URI : https://www.diandian100.cn
# @File : selenium解锁文字验证阿妈.py
# @Desc :
import json
import random
import time

import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By


def base64_api(uname, pwd, img_base64, typeid):
"""
获取验证码缺口
:param uname: 646547989
:param pwd: 646547989
:param img_base64: selenium可直接拿到验证码base64
:param typeid: 27
:return:|分割的坐标组
"""
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 is_show_coordinate():
"""判断是否中文坐标验证码"""
if "依次点击文字" in driver.page_source:
# 获取整个验证码dom
verify_dom = driver.find_element(By.XPATH, '//*[@id="captcha_container"]/div')
# 整个验证码dom转为图片base64
verify_base64 = verify_dom.screenshot_as_base64
# 请求中文验证文字坐标
result = base64_api(uname='您的用户名', pwd='您的密码', img_base64=verify_base64, typeid=27)
# 分割每个文字坐标(相对于dom)
positions = result.split("|")
print("文字坐标:", positions)
# 依次循环点击每个文字
for p in positions:
# 获取当前文字坐标值
x, y = p.split(',')
# 鼠标移动到当前dom中x、y坐标并点击
ActionChains(driver).move_to_element_with_offset(verify_dom, x, y).click().perform()
# 延时点击下一个文字(2秒以内)
time.sleep(random.random() * 2)
# 点击中文验证码,点击确定按钮,完成验证
verify_dom.find_element(By.XPATH, 'div[3]/div[2]').click()


if __name__ == '__main__':
option = webdriver.ChromeOptions()
# 模拟真正浏览器
option.add_experimental_option('excludeSwitches', ['enable-automation'])
# chrome驱动服务
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)
# 向下滑动一屏
driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
# 休眠10秒钟
time.sleep(10)
# 是否有中文验证码
is_show_coordinate()
time.sleep(1000)