验证码部分参考https://github.com/ybsdegit/captcha_qq
使用前,设置为100%
验证码部分可以通过调速度来达到想要的速度,速度不建议过快,否则会被检测为人机
实际效果:https://www.bilibili.com/video/BV1CE411M7ym
import numpy as np
import random
import requests
from selenium.webdriver import ActionChains
import time
from selenium import webdriver
from PIL import Image
import os
from selenium.webdriver.support.ui import WebDriverWait
import cv2
import re
import numpy as np
from cv2 import cv2 as cv2
from matplotlib import pyplot as plt
class Login(object):
def __init__(self):
self.url = "https://cf.qq.com/cp/a20200219pull/index.shtml"
self.driver = webdriver.Chrome()
@staticmethod
def show(name):
cv2.imshow('Show', name)
cv2.waitKey(0)
cv2.destroyAllWindows()
@staticmethod
def 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)
@staticmethod
def webdriverwait_click(dri, element):
"""
显示等待 click
:param dri: driver
:param element:
:return:
"""
WebDriverWait(dri, 10, 5).until(lambda dr: element).click()
@staticmethod
def get_postion(chunk, canves):
"""
判断缺口位置
:param chunk: 缺口图片是原图
:param canves:
:return: 位置 x, y
"""
otemp = chunk
oblk = canves
target = 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)
x, y = np.unravel_index(result.argmax(), result.shape)
cv2.rectangle(template, (y, x), (y + w, x + h), (7, 249, 151), 2)
cv2.imwrite("yuantu.jpg", template)
plt.figure("new")
plt.imshow(template)
plt.show()
return x, y
# 展示圈出来的区域
@staticmethod
def get_track(distance):
"""
模拟轨迹 假装是人在操作
:param distance:
:return:
"""
# 初速度
v = 20
# 单位时间为0.2s来统计轨迹,轨迹即0.2内的位移
t = 0.2
# 位移/轨迹列表,列表内的一个元素代表0.2s的位移
tracks = []
# 当前的位移
current = 0
da1,da2 = 20,30
while current < distance:
a = (random.randint(da1, da2))%50 # 加速运动
# 初速度
v0 = v
# 0.2秒时间内的位移
s = v0 * t + 0.5 * a * (t ** 2)
# 当前的位置
current += round(s)
# 添加到轨迹列表
tracks.append(round(s))
# 速度已经达到v,该速度作为下次的初速度
v = v0 + a * t
v=0
tracks.append(distance-current)
return tracks
@staticmethod
def urllib_download(imgurl, imgsavepath):
"""
下载图片
:param imgurl: 图片url
:param imgsavepath: 存放地址
:return:
"""
from urllib.request import urlretrieve
urlretrieve(imgurl, imgsavepath)
def after_quit(self):
"""
关闭浏览器
:return:
"""
self.driver.quit()
def is_element_exist(self,driver,element):
try:
driver.find_element_by_id(element)
return True
except Exception as err:
print(err)
return False
def login_main(self):
# ssl._create_default_https_context = ssl._create_unverified_context
driver = self.driver
driver.maximize_window()
driver.get(self.url)
while True:
time.sleep(0.5)
if self.is_element_exist(driver,"loginIframe"):# 如果没有登陆
driver.switch_to.frame("loginIframe")
login = driver.find_element_by_class_name("face")
self.webdriverwait_click(driver, login)
# 切回去
driver.switch_to.parent_frame()
time.sleep(2)
elments = driver.find_elements_by_class_name("btn-get-251")
index = 0
for i in range(len(elments)):
if elments[i].get_attribute("href") == "javascript:getLottery(644854,'','loadOut()','','');":
print("找到武器")
index = i
break
# 移动到指定位置
ActionChains(driver).move_to_element(elments[index]).perform()
# 点击领取
self.webdriverwait_click(driver,elments[index])
#等待验证码
time.sleep(1.5)
driver.switch_to.frame(driver.find_element_by_id('tcaptcha_iframe')) # switch 到 滑块frame
while True:
bk_block = driver.find_element_by_xpath('//img[@id="slideBg"]') # 大图
web_image_width = bk_block.size
web_image_width = web_image_width['width']
bk_block_x = bk_block.location['x']
slide_block = driver.find_element_by_xpath('//img[@id="slideBlock"]') # 小滑块
slide_block_x = slide_block.location['x']
web_imageSlideBlock_width = slide_block.size
web_imageSlideBlock_width = web_imageSlideBlock_width['width']
bk_block = driver.find_element_by_xpath('//img[@id="slideBg"]').get_attribute('src') # 大图 url
slide_block = driver.find_element_by_xpath('//img[@id="slideBlock"]').get_attribute('src') # 小滑块 图片url
slid_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)
position = self.get_postion('./image/bkBlock.png', './image/slideBlock.png')
print("原图距离:",position[1],"width_scale:",width_scale,"背景图宽:",real_width,"web上:",web_image_width)
real_position = position[1] / width_scale
real_position = real_position - 26
print("slide_block_x",slide_block_x,"bk_block_x",bk_block_x)
track_list = self.get_track(real_position*0.25)
ActionChains(driver).click_and_hold(on_element=slid_ing).perform() # 点击鼠标左键,按住不放
time.sleep(0.2)
print('第二步,拖动元素')
ActionChains(driver).move_by_offset(xoffset=real_position*0.75, yoffset=0).perform()
for track in track_list:
ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform() # 鼠标移动到距离当前位置(x,y)
time.sleep(0.02)
# ActionChains(driver).move_by_offset(xoffset=-random.randint(0, 1), yoffset=0).perform() # 微调,根据实际情况微调
time.sleep(0.1)
# print('第三步,释放鼠标')
ActionChains(driver).release(on_element=slid_ing).perform()
time.sleep(2)
print("实际距离",real_position)
print(track_list)
print('点击完成')
#print(self.is_element_exist(driver,"lotteryAlertDialog"))
#if driver.find_element_by_id("lotteryAlertDialog")!=None:
#driver.refresh()
#break
self.after_quit()
if __name__ == '__main__':
login = Login()
login.login_main()