写爬虫很多时候会遇到滑块验证码
比如这样的
import os
import requests
import time
import random
import json
from PIL import Image
from PIL import ImageGrab
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.action_chains import ActionChains
# 匹配到原图,对原图进行操作
def match_source(image, source_path='./sources'):
#image是验证码图片
# 遍历文件夹下面的所有图片
for source in sorted(os.listdir(source_path)):
source_img = Image.open(os.path.join(source_path, source))
# 根据自己电脑的实际情况调整
pixel1 = image.getpixel((846, 429))
pixel2 = source_img.getpixel((846, 429))
if abs(pixel1[0]-pixel2[0]) < 5:
print('当前匹配的地图是',source)
return source_img
return None
# 截取当前验证码图片
def capture_captcha(browser, savename='captcha.png'):
'''
captcha = WebDriverWait(browser, 60).until(expected_conditions.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))
# location = captcha.location
# size = captcha.size
# top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size['width']
# print('[INFO]: Captcha location - (top, bottom, left, right) -> ({}, {}, {}, {})'.format(top, bottom, left, right))
time.sleep(1)
left, top, right, bottom = 790, 280, 1100, 480
screenshot = browser.get_screenshot_as_png()
screenshot = Image.open(BytesIO(screenshot))
screenshot.save('sd.png')
captcha_img = screenshot.crop((left, top, right, bottom))
captcha_img.save(savename)
return savename
'''
time.sleep(0.5)
WebDriverWait(browser, 60).until(expected_conditions.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))
slider = browser.find_element_by_class_name('geetest_slider_button')
x = slider.location