此代码请勿用来商用,后果自负。
仅供学习。
文章参考:/qq_38534107/article/details/89522481
import numpy as npimport randomimport requestsfrom selenium.webdriver import ActionChainsimport timefrom selenium import webdriverfrom PIL import Imageimport osfrom selenium.webdriver.support.ui import WebDriverWaitimport cv2class Login(object):"""腾讯防水墙滑动验证码破解使用OpenCV库成功率大概90%左右:在实际应用中,登录后可判断当前页面是否有登录成功才会出现的信息:比如用户名等。循环https://open./online.html破解 腾讯滑动验证码腾讯防水墙python + seleniuum + cv2"""def __init__(self):# 如果是实际应用中,可在此处账号和密码self.url = "https://open./online.html"self.driver = webdriver.Chrome()@staticmethoddef show(name):cv2.imshow('Show', name)cv2.waitKey(0)cv2.destroyAllWindows()@staticmethoddef webdriverwait_send_keys(dri, element, value):"""显示等待输入:param dri: driver:param element::param value::return:"""WebDriverWait(dri, 10, 5).until(lambda dr: element).send_keys(value)@staticmethoddef webdriverwait_click(dri, element):"""显示等待 click:param dri: driver:param element::return:"""WebDriverWait(dri, 10, 5).until(lambda dr: element).click()@staticmethoddef get_postion(chunk, canves):"""判断缺口位置:param chunk: 缺口图片是原图:param canves::return: 位置 x, y"""otemp = chunkoblk = canvestarget = cv2.imread(otemp, 0)template = cv2.imread(oblk, 0)# w, h = target.shape[::-1]temp = 'temp.jpg'targ = 'targ.jpg'cv2.imwrite(temp, template)cv2.imwrite(targ, target)target = cv2.imread(targ)target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)target = abs(255 - target)cv2.imwrite(targ, target)target = cv2.imread(targ)template = cv2.imread(temp)result = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED)print(f'result是{result}')x, y = np.unravel_index(result.argmax(), result.shape)print(f'x,y:{x},{y}')return x, y# # 展示圈出来的区域# cv2.rectangle(template, (y, x), (y + w, x + h), (7, 249, 151), 2)# cv2.imwrite("yuantu.jpg", template)# show(template)@staticmethoddef get_track(distance):"""模拟轨迹 假装是人在操作:param distance::return:"""# 初速度v = 0# 单位时间为0.2s来统计轨迹,轨迹即0.2内的位移t = 0.2# 位移/轨迹列表,列表内的一个元素代表0.2s的位移tracks = []# 当前的位移current = 0# 到达mid值开始减速mid = distance * 7 / 8distance += 10 # 先滑过一点,最后再反着滑动回来# a = random.randint(1,3)while current < distance:if current < mid:# 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细a = random.randint(2, 4) # 加速运动else:a = -random.randint(3, 5) # 减速运动# 初速度v0 = v# 0.2秒时间内的位移s = v0 * t + 0.5 * a * (t ** 2)# 当前的位置current += s# 添加到轨迹列表tracks.append(round(s))# 速度已经达到v,该速度作为下次的初速度v = v0 + a * t# 反着滑动到大概准确位置for i in range(4):tracks.append(-random.randint(2, 3))for i in range(4):tracks.append(-random.randint(1, 3))return tracks@staticmethoddef urllib_download(imgurl, imgsavepath):"""下载图片:param imgurl: 图片url:param imgsavepath: 存放地址:return:"""from urllib.request import urlretrieveurlretrieve(imgurl, imgsavepath)def after_quit(self):"""关闭浏览器:return:"""self.driver.quit()def login_main(self):# ssl._create_default_https_context = ssl._create_unverified_contextdriver = self.driverdriver.maximize_window()driver.get(self.url)click_keyi_username = driver.find_element_by_xpath("//div[@class='wp-onb-tit']/a[text()='可疑用户']")self.webdriverwait_click(driver, click_keyi_username)login_button = driver.find_element_by_id('code')self.webdriverwait_click(driver, login_button)time.sleep(1)driver.switch_to.frame(driver.find_element_by_id('tcaptcha_iframe')) # switch 到 滑块frametime.sleep(0.5)bk_block = driver.find_element_by_xpath('//img[@id="slideBg"]') # 大图web_image_width = bk_block.sizeweb_image_width = web_image_width['width']bk_block_x = bk_block.location['x']print(f'大图的width{web_image_width},它的x坐标{bk_block_x}')slide_block = driver.find_element_by_xpath('//img[@id="slideBlock"]') # 小滑块slide_block_x = slide_block.location['x']print(f'小滑块的x坐标{slide_block_x}')bk_block = driver.find_element_by_xpath('//img[@id="slideBg"]').get_attribute('src') # 大图 urlslide_block = driver.find_element_by_xpath('//img[@id="slideBlock"]').get_attribute('src') # 小滑块 图片urlslid_ing = driver.find_element_by_xpath('//div[@id="tcaptcha_drag_thumb"]') # 滑块os.makedirs('./image/', exist_ok=True)self.urllib_download(bk_block, './image/bkBlock.png')self.urllib_download(slide_block, './image/slideBlock.png')time.sleep(0.5)#网站验证码缩小倍数img_bkblock = Image.open('./image/bkBlock.png')real_width = img_bkblock.size[0]width_scale = float(real_width) / float(web_image_width)#获取背景图缺口坐标x,yposition = self.get_postion('./image/bkBlock.png', './image/slideBlock.png')#获取移动距离,因为是缩小的,网页版距离也需要缩小real_position = position[1] / width_scaleprint(position[1])real_position = real_position - (slide_block_x - bk_block_x)#获取运动轨迹列表track_list = self.get_track(real_position + 4)ActionChains(driver).click_and_hold(on_element=slid_ing).perform() # 点击鼠标左键,按住不放time.sleep(0.2)# print('第二步,拖动元素')for track in track_list:ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform() # 鼠标移动到距离当前位置(x,y)time.sleep(0.002)# ActionChains(driver).move_by_offset(xoffset=-random.randint(0, 1), yoffset=0).perform() # 微调,根据实际情况微调time.sleep(1)# print('第三步,释放鼠标')ActionChains(driver).release(on_element=slid_ing).perform()time.sleep(1)print('登录成功')self.after_quit()if __name__ == '__main__':phone = "****"login = Login()login.login_main()