Python爬虫入门教程 59-100 python爬虫高级技术之验证码篇5-极验证识别技术之二

1. 云栖社区>
2. python技术进阶>
3. 博客>
4. 正文

@[toc]

## 图片比对

### 计算缺口坐标

``````    def get_distance(self,cut_image,full_image):

# print(cut_image.size)
threshold = 50
for i in range(0,cut_image.size[0]):
for j in range(0,cut_image.size[1]):
pixel1 = cut_image.getpixel((i, j))
pixel2 = full_image.getpixel((i, j))
res_R = abs(pixel1[0] - pixel2[0])  # 计算RGB差
res_G = abs(pixel1[1] - pixel2[1])  # 计算RGB差
res_B = abs(pixel1[2] - pixel2[2])  # 计算RGB差

if res_R > threshold and res_G > threshold and res_B > threshold:
return i  # 需要移动的距离
``````

https://blog.csdn.net/ieternite/article/details/51483491

https://www.cnblogs.com/xiao-apple36/p/8878960.html

### 移动滑块

``````    # 移动滑块
def start_move(self, distance):
element = self.driver.find_element_by_xpath('//div[@class="gt_slider_knob gt_show"]')

# 使用滑块的一半进行偏移设置
distance -= element.size.get('width') / 2
distance += 15

# 按下鼠标左键
ActionChains(self.driver).click_and_hold(element).perform()
time.sleep(0.5)
while distance > 0:
if distance > 20:
# 如果距离大于20，就让他移动快一点
span = random.randint(5, 8)
else:
# 快到缺口了，就移动慢一点
span = random.randint(2, 3)
ActionChains(self.driver).move_by_offset(span, 0).perform()
distance -= span
time.sleep(random.randint(10, 50) / 100)

ActionChains(self.driver).move_by_offset(distance, 1).perform()
ActionChains(self.driver).release(on_element=element).perform()
``````

### 验证失败

``````       self.start_move(dis)

# 如果出现错误
try:
WebDriverWait(self.driver, 5).until(
EC.element_to_be_clickable((By.XPATH, '//div[@class="gt_ajax_tip gt_error"]')))
print("验证失败")
return
except TimeoutException as e:
pass

# 判断是否验证成功
try:
WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//div[@class="gt_ajax_tip gt_success"]')))
except TimeoutException:
print("重新验证....")
time.sleep(5)
# 失败后递归执行拖动
self.analog_drag()
else:
print("验证成功")
``````

## 写在后面

``````element = self.driver.find_element_by_xpath('//div[@class="gt_slider_knob gt_show"]')
``````

driver 需要及时的关闭，否则会在你的任务管理器中出现大量的`chromedriver.exe` 进程