網(wǎng)站需要驗(yàn)證碼Python簡(jiǎn)單測(cè)試自動(dòng)通過(guò)驗(yàn)證
網(wǎng)站需要驗(yàn)證碼Python簡(jiǎn)單測(cè)試自動(dòng)通過(guò)驗(yàn)證
隨著技術(shù)的發(fā)展,驗(yàn)證碼越來(lái)越復(fù)雜,接下來(lái)我們解決常用的幾種,需要用到的庫(kù)有selenium、PIL
通??梢允褂胦penca或者tesserocr,但是對(duì)于新手來(lái)說(shuō),他們的安裝和使用有些難度。下面就介紹一個(gè)更加簡(jiǎn)單的ddddocr,首先是安裝:
pip?install?ddddocr
為了演示效果,我們這里提前準(zhǔn)備好了一個(gè)圖片驗(yàn)證碼
from?selenium?import?webdriver from?selenium.webdriver?import?ActionChains import?time from?PIL?import?Image #?初始化?Chrome?瀏覽器 driver?=?webdriver.Chrome() driver.maximize_window() #?打開(kāi)目標(biāo)網(wǎng)站,等待加載 driver.get("https://test.com/") time.sleep(1) #?選擇賬號(hào)、密碼輸入欄,輸入對(duì)應(yīng)的賬號(hào)密碼 input_user=driver.find_element_by_xpath('//input[@name="username"]') input_user.send_keys('賬號(hào)') input_pwd=driver.find_element_by_xpath('//input[@name="password"]') #?輸入密碼 input_pwd.send_keys('密碼') #?將當(dāng)前頁(yè)面截圖 driver.save_screenshot('code.png') #?選擇驗(yàn)證碼圖片的元素 code_btn?=?driver.find_element_by_xpath('//input[@name="password"]/span') #?獲取圖片元素的位置 loc?=?code_btn.location #?獲取圖片的寬高 size?=?code_btn.size #?獲取驗(yàn)證碼上下左右的位置 left?=?loc['x']*1.25 top?=?loc['y']*1.25 right?=?(loc['x']?+?size['width'])*1.25 botom?=?(loc['y']?+?size['height'])*1.25 val?=?(left,?top,?right,?botom) #?打開(kāi)網(wǎng)頁(yè)截圖 login_pic?=?Image.open('code.png') #?通過(guò)上下左右的值,去截取驗(yàn)證碼 code_img?=?login_pic.crop(val) code_img.save('code.png') #?識(shí)別驗(yàn)證碼 with?open('code.png,'rb')?as?f: ????img_content?=?f.read() result?=?ddddocr.Dddd0cr(res?=?ocr.classification(img_bytes) code=res[-4:]?#看你的驗(yàn)證碼是幾位,截取驗(yàn)證碼后4位 #?在輸入框輸入驗(yàn)證碼 driver.find_element_by_xpath('/html/body/div[3]/form/p/input') yzm_input.send_keys(code) #?點(diǎn)擊登錄 submit?=?driver.find_element_by_xpath('/input[@class="submit"]/input') submit.click() #?等待?2?秒鐘查看結(jié)果 time.sleep(2) #?關(guān)閉瀏覽器 driver.quit()
使用selenium打開(kāi)瀏覽器來(lái)模擬這個(gè)滑動(dòng)流程
from?selenium?import?webdriver from?selenium.webdriver?import?ActionChains import?time #?初始化?Chrome?瀏覽器 driver?=?webdriver.Chrome() driver.maximize_window() #?打開(kāi)目標(biāo)網(wǎng)站,等待加載 driver.get("https://test.com/") time.sleep(1) #?定位滑塊元素和背景圖片元素 slider?=?driver.find_element_by_xpath("//*[@id='slider']") bg?=?driver.find_element_by_xpath("//*[@id='sliderBackground']") #?計(jì)算滑塊需要移動(dòng)的距離 distance?=?slider.location['x']?-?bg.location['x'] #?模擬人的拖動(dòng)操作 action?=?ActionChains(driver) action.click_and_hold(slider).perform() action.move_by_offset(distance,?0).perform() action.release().perform() #?等待?5?秒鐘查看結(jié)果 time.sleep(5) #?關(guān)閉瀏覽器 driver.quit()