Selenium爬虫遇到验证码的处理
整体思路:
1、保存登录页面以png格式driver.save_screenshot(“img/ym.png”)
2、对页面中的验证码区域进行定位截取保存
3、对验证码图片进行处理掉用pytesseract进行验证码识别
4、判断验证码结果是否成功,未成功点击图片重新进行识别
import time
from selenium import webdriver
from PIL import Image,ImageEnhance
import pytesseract
url = 'https://www.tfswufe.edu.cn/'
driver = webdriver.Chrome(executable_path='/Users/denglu/PycharmProjects/new/chromedriver')
driver.implicitly_wait(2) #隐式等待
driver.get(url)
# 验证码识别函数,传入的driver为selenium页面句柄
def yzm(driver):
# 保存整个页面为png
driver.save_screenshot("img/ym.png")
#通过xpath找到图片的位置定位,根据自己情况修改xpath地址
img = driver.find_element_by_xpath('//*[@id="fm1"]/div[1]/section[2]/div[1]/span/img')
#获取图片的相对位置left,top 然后计算right,bottom
left = img.location['x']
top = img.location['y']
right = img.location['x'] + img.size['width']
bottom = img.location['y'] + img.size['height']
#打开页面png,通过crop函数截取到验证码区域
im = Image.open('img/ym.png')
im = im.crop((left, top, right, bottom))
#保存验证码图片
im.save('img/yzm.png')
# 验证码识别,打开验证码对图像进行处理,
imageCode = Image.open("img/yzm.png") # 图像增强,二值化
sharp_img = ImageEnhance.Contrast(imageCode).enhance(2.0)
sharp_img.save("img/yzm_c.png")
sharp_img.load() # 对比度增强
# 验证码识别,使用pytesseract.image_tostring(img).strip()
code = pytesseract.image_to_string(sharp_img).strip()
print('验证码识别为:' + str(code))
return code
#调用函数有情况出现识别为空,如果验证码识别失败,点击图片重新进行识别,
code = yzm(driver)
while code=="":
driver.find_element_by_xpath('//*[@id="fm1"]/div[1]/section[2]/div[1]/span/img').click()
code = yzm(driver)