大神勿噴 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time from PIL import Image from PIL import ImageEnhance import pytesseract b = webdriver.Firefox() b.get("http://www.ouchn.cn/") 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") #打開截圖 frame4=i.crop(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 = sharpness.enhance(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方法可定位長寬大小,但我在使用過程中發現這兩個方法都不行,直接報錯(一年后偶然發現跟驅動有關系)。后來偶然發現了location的哥哥location_once_scrolled_into_view,試了一下,沃插,居然能定位出坐標。但size方法還是不行,后來通過審查元素發現也可以發現圖片元素的長寬大小。最后試了幾下終於能精確截取驗證碼圖片經行識別。