本人纯野生测试猿一头,做了一年web 功能测试,测试了一年机顶盒,还是想做回老本行 ,自学了一段时间selenium ,学习过程中,遇到了网页中需要输入验证码的问题,网上查阅资料,依葫芦画瓢凑成(水平有限)了一段登陆网站挂课的脚本(亲测通过),现跟大家分享如下:
大神勿喷
from selenium import webdriver
from selenium.webdrivermon.action_chains import ActionChains
import time
from PIL import Image
from PIL import ImageEnhance
import pytesseract
b = webdriver.Firefox()
<("/")time.sleep(5)
ele = b.find_element_by_css_selector
("html body div#ding div.din div.di2 a.loginbtn")
#print(type(ele))
ele.click()#点击登录
time.sleep(8)
#print(b.window_handles)
b.switch_to_window(b.window_handles[1])
#print(b.current_url)
#b.get(b.current_url)
b.save_screenshot(‘E://aa.png‘) #截取当前网页,该网页有我们需要的验证码
time.sleep(6)
imgelement = b.find_element_by_css_selector("html body form div#box div.box div.kk table tbody tr td label img") #定位验证码
location1 = imgelement.location_once_scrolled_into_view
print(location1)
coderange=(int(location1[‘x‘]),int(location1[‘y‘]+100),int((location1[‘x‘]-30)+130),int((location1[‘y‘]+130))) #写成我们需要截取的位置坐标
i=Image.open(r"E:aa.png") #打开截图
frame4p(coderange) #使用Image的crop函数,从截图中再次截取我们需要的区域
frame4.save(r"E:frame4.png")
i2=Image.open(r"E:frame4.png")
imgry = i2.convert(‘L‘) #图像加强,二值化,PIL中有九种不同模式。分别为1,L,P,RGB,RGBA,CMYK,YCbCr,I,F。L为灰度图像
sharpness =ImageEnhance.Contrast(imgry)#对比度增强
i3 = hance(3.0) #3.0为图像的饱和度
i3.save("E:\image_code.png")
i4 = Image.open("E:\image_code.png")
text = pytesseract.image_to_string(i4).strip() #使用image_to_string识别验证码
print(text)#调试用,查看验证码识别是否成功
b.find_element_by_id("username").clear()
b.find_element_by_id("username").send_keys("此处马赛克")
b.find_element_by_id("password").send_keys("此处马赛克")
b.find_element_by_css_selector("html body form div#box div.box div.kk table tbody tr td label ")
"input#checkCode.biaodan2").send_keys(text)
time.sleep(5)
b.find_element_by_css_selector("html body form div#box div.box div.kk table tbody tr td table tbody tr td label input#btnLogin.anniu").click()
#b.quit()
途中看到网上的大神用location方法就可定位图片元素位置、用size方法可定位长宽大小,但我在使用过程中发现这两个方法都不行,直接报错(我用的python3,可能跟这个有关)。后来偶然发现了location的哥哥location_once_scrolled_into_view,试了一下,沃插,居然能定位出坐标。但size方法还是不行,后来通过审查元素发现也可以发现图片元素的长宽大小。最后试了几下终于能精确截取验证码图片经行识别。
原文:.html
本文发布于:2024-02-01 13:40:14,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170676601436999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |