打開對應(yīng)網(wǎng)站,走到滑塊驗(yàn)證處 勋陪;
設(shè)置顯性等待皮服,找到滑塊圖片加載完畢 WebDriverWait.until;
class yanzhengma:
def __init__(self):
self.url = 'https://passport.xfyun.cn/login'
self.browser = webdriver.Chrome()
self.browser.maximize_window()
self.wait = WebDriverWait(self.browser, 5)
self.success = False
self.try_num = 2
self.now_num = 2
self.flesh_num = 1
def run(self):
self.browser.get(self.url)
獲取圖片上下左右邊距離窗口的位置 img.location img.size逢防;
def get_position(self):
"""
獲取驗(yàn)證碼位置
:return: 驗(yàn)證碼位置元組
"""
img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))
time.sleep(1)
location = img.location
size = img.size
top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size['width']
return top, bottom, left, right
截取滑塊驗(yàn)證的圖片 driver.get_screenshot_as_png();
screenshot = self.browser.get_screenshot_as_png()
讀取圖片的RGB順序蒲讯,并切割 Image.open Image.crop忘朝;
screenshot = Image.open(BytesIO(screenshot))
獲取缺口的偏移量;
def get_gap(self, image):
"""
獲取缺口偏移量
:param image: 帶缺口圖片
:return:
"""
for i in [10 * i for i in range(1, 14)]:
for j in range(50, image.size[0] - 30):
if self.is_pixel_equal(image, j, i):
break
return left_list
判斷缺口偏移量;
@staticmethod
def is_pixel_equal(image, x, y):
"""
判斷兩個(gè)像素是否相同
:param image: 圖片
:param x: 位置x
:param y: 位置y
:return: 像素是否相同
"""
x_max = image.size[0]
# 取兩個(gè)圖片的像素點(diǎn)
pixel1 = image.load()[x, y]
threshold = 150
count = 0
if pixel1[0] < threshold and pixel1[1] < threshold and pixel1[2] < threshold:
for i in range(x + 1, image.size[0]):
piexl = image.load()[i, y]
if piexl[0] < threshold and piexl[1] < threshold and piexl[2] < threshold:
count += 1
else:
break
if int(x_max / 8.6) < count < int(x_max / 4.3):
left_list.append((x, count))
return True
else:
return False
根據(jù)偏移量獲取移動(dòng)軌跡;
@staticmethod
def get_track(distance):
"""
根據(jù)偏移量獲取移動(dòng)軌跡
:param distance: 偏移量
:return: 移動(dòng)軌跡
"""
# 移動(dòng)軌跡
track = []
# 當(dāng)前位移
current = 0
# 減速閾值
mid = distance * 4 / 5
# 計(jì)算間隔
t = 0.2
# 初速度
v = 0
while current < distance:
if current < mid:
# 加速度為正2
a = 2
else:
# 加速度為負(fù)3
a = -3
# 初速度v0
v0 = v
# 當(dāng)前速度v = v0 + at
v = v0 + a * t
# 移動(dòng)距離x = v0t + 1/2 * a * t^2
move = v0 * t + 1 / 2 * a * t * t
# 當(dāng)前位移
current += move
# 加入軌跡
track.append(round(move))
return track
獲取滑塊元素,拖動(dòng)滑塊 ActionChains();
ActionChains(self.browser).click_and_hold(slider).perform()
for x in track:
ActionChains(self.browser).move_by_offset(xoffset=x, yoffset=0).perform()
ActionChains(self.browser).release().perform()
當(dāng)前實(shí)現(xiàn)代碼及缺陷:
import time
from io import BytesIO
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image
left_list = []
BORDER_1 = 7
BORDER_2 = 12
class yanzhengma:
def __init__(self):
self.url = 'https://passport.xfyun.cn/login'
self.browser = webdriver.Chrome()
self.browser.maximize_window()
self.wait = WebDriverWait(self.browser, 5)
self.success = False
self.try_num = 2
self.now_num = 2
self.flesh_num = 1
# 獲取驗(yàn)證碼圖片
def get_geetest_image(self, name='captcha.png'):
"""
獲取驗(yàn)證碼圖片
:return: 圖片對象
"""
top, bottom, left, right = self.get_position()
print(top, bottom, left, right)
screenshot = self.browser.get_screenshot_as_png()
screenshot = Image.open(BytesIO(screenshot))
captcha = screenshot.crop((left, top, right, bottom))
captcha.save(name)
return captcha
# 獲取截圖中驗(yàn)證碼的上下左右的位置
def get_position(self):
"""
獲取驗(yàn)證碼位置
:return: 驗(yàn)證碼位置元組
"""
img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))
time.sleep(1)
location = img.location
size = img.size
top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size['width']
return top, bottom, left, right
# 獲取網(wǎng)頁截圖
def get_screenshot(self):
"""
獲取網(wǎng)頁截圖
:return: 截圖對象
"""
screenshot = self.browser.get_screenshot_as_png()
screenshot = Image.open(BytesIO(screenshot))
return screenshot
# 獲取缺口偏移量
def get_gap(self, image):
"""
獲取缺口偏移量
:param image: 帶缺口圖片
:return:
"""
for i in [10 * i for i in range(1, 14)]:
for j in range(50, image.size[0] - 30):
if self.is_pixel_equal(image, j, i):
break
return left_list
# 判斷缺口偏移量
@staticmethod
def is_pixel_equal(image, x, y):
"""
判斷兩個(gè)像素是否相同
:param image: 圖片
:param x: 位置x
:param y: 位置y
:return: 像素是否相同
"""
x_max = image.size[0]
# 取兩個(gè)圖片的像素點(diǎn)
pixel1 = image.load()[x, y]
threshold = 150
count = 0
if pixel1[0] < threshold and pixel1[1] < threshold and pixel1[2] < threshold:
for i in range(x + 1, image.size[0]):
piexl = image.load()[i, y]
if piexl[0] < threshold and piexl[1] < threshold and piexl[2] < threshold:
count += 1
else:
break
if int(x_max / 8.6) < count < int(x_max / 4.3):
left_list.append((x, count))
return True
else:
return False
# 根據(jù)偏移量獲取移動(dòng)軌跡
@staticmethod
def get_track(distance):
"""
根據(jù)偏移量獲取移動(dòng)軌跡
:param distance: 偏移量
:return: 移動(dòng)軌跡
"""
# 移動(dòng)軌跡
track = []
# 當(dāng)前位移
current = 0
# 減速閾值
mid = distance * 4 / 5
# 計(jì)算間隔
t = 0.2
# 初速度
v = 0
while current < distance:
if current < mid:
# 加速度為正2
a = 2
else:
# 加速度為負(fù)3
a = -3
# 初速度v0
v0 = v
# 當(dāng)前速度v = v0 + at
v = v0 + a * t
# 移動(dòng)距離x = v0t + 1/2 * a * t^2
move = v0 * t + 1 / 2 * a * t * t
# 當(dāng)前位移
current += move
# 加入軌跡
track.append(round(move))
return track
# 獲取滑塊對象
def get_slider(self):
"""
獲取滑塊
:return: 滑塊對象
"""
try:
slider = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_slider_button')))
except Exception:
return
return slider
def run(self):
self.browser.get(self.url)
time.sleep(3)
self.browser.find_element_by_xpath('//*[@id="app"]/div/section/div/div/div[2]/div/div[1]/div[2]/div[1]/div/div/div/div/div[1]/div[3]').click()
self.browser.find_element_by_id('username').send_keys('16619942153')
time.sleep(0.5)
self.browser.find_element_by_id('password').send_keys('sj7845464')
time.sleep(0.5)
self.browser.find_element_by_xpath('//*[@id="app"]/div/section/div/div/div[2]/div/div[2]/div/form/button').click()
time.sleep(3)
# while not self.success and self.now_num > 0:
error_list = [5, 7, 10]
for i in range(3):
try:
image = self.get_geetest_image()
except:
break
left_list = self.get_gap(image)
#----------------------------------------------------
x_max = image.size[0]
left_list = sorted(left_list, key=lambda x: abs(x[1] - int(x_max / 6.45)))
print(left_list)
if not left_list:
print("left_lsit為空, 無法獲取gap")
break
gap = left_list[0][0]
print('gap:', gap)
# 計(jì)算滑動(dòng)距離
track = self.get_track(int(gap) - error_list[i])
# 拖動(dòng)滑塊
slider = self.get_slider()
print('位移list:', track)
ActionChains(self.browser).click_and_hold(slider).perform()
for x in track:
ActionChains(self.browser).move_by_offset(xoffset=x, yoffset=0).perform()
ActionChains(self.browser).release().perform()
if __name__ == "__main__":
y = yanzhengma()
y.run()
缺陷:
1.存在滑塊無法滑到至合適的位置判帮;
2.滑動(dòng)速度太均勻辜伟,需要改變方式模擬人為動(dòng)作軌跡繞過機(jī)器檢驗(yàn)。