国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python +Selenium解決圖片驗證碼登錄或注冊問題(推薦)

2020-02-15 21:19:07
字體:
來源:轉載
供稿:網友

1. 解決思路

首先要獲得這張驗證碼的圖片,但是該圖片一般都是用的js寫的,不能夠通過url進行下載。
解決方案:截圖然后根據該圖片的定位和長高,使用工具進行裁剪
裁剪完畢之后,使用工具解析該圖片。

2. 代碼實現

2.1 裁剪出驗證碼圖片

裁剪圖片需要使用 Pillow 庫,進入pip包路徑后輸入安裝命令pip install Pillow:
之前安裝的時候忘記了截圖,只能夠截一張安裝后的圖片了 ╰(:з╰∠)_

安裝完成后,代碼實現方式如下:

#coding=utf-8from selenium import webdriverimport timefrom PIL import Imagefrom selenium.webdriver.support.wait import WebDriverWaitdriver = webdriver.Chrome()# 進入該網站driver.get("http://www2.nmec.org.cn/wangbao/nme/sp/root/account/signup.html")# 能否在5s內找到驗證碼元素,能才繼續if WebDriverWait(driver,5).until(lambda the_driver:the_driver.find_element_by_id("CaptchaImg"), "查找不到該元素"): # 對于一次截屏無法到截到驗證碼的情況,需要滾動一段距離,然后驗證碼的y坐標也應該減去這段距離 scroll = 500 js = "document.documentElement.scrollTop='%s'" %scroll driver.execute_script(js) # 截下該網站的圖片 driver.get_screenshot_as_file("E:/Python_selenium_advance/Picture/full.png") # 獲得這個圖片元素 img_ele = driver.find_element_by_id("CaptchaImg") # 得到該元素左上角的 x,y 坐標和右下角的 x,y 坐標 left = img_ele.location.get('x') upper = img_ele.location.get('y') - 500 right = left + img_ele.size.get('width') lower = upper + img_ele.size.get('height') # 打開之前的截圖 img = Image.open("E:/Python_selenium_advance/Picture/full.png") # 對截圖進行裁剪,裁剪的范圍為之前驗證的左上角至右下角范圍 new_img = img.crop((left, upper, right, lower)) # 裁剪完成之后保存到指定路徑 new_img.save("E:/Python_selenium_advance/Picture/croped.png")  time.sleep(2) driver.quit()else: print("找不到驗證碼元素")

2.2 使用 圖鑒 商用接口來識別驗證碼

接口介紹網址:http://www.ttshitu.com/docs/python.html#pageTitle

調用該接口直接使用網頁上的接口文檔就行,代碼如下:

import jsonimport requestsimport base64from io import BytesIOfrom PIL import Imagefrom sys import version_infodef base64_api(uname, pwd, softid, img): img = img.convert('RGB') buffered = BytesIO() img.save(buffered, format="JPEG") if version_info.major >= 3:  b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8') else:  b64 = str(base64.b64encode(buffered.getvalue())) data = {"username": uname, "password": pwd, "softid": softid, "image": b64} result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text) if result['success']:  return result["data"]["result"] else:  return result["message"] return ""
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 成武县| 泌阳县| 安西县| 塘沽区| 峨边| 潼关县| 牙克石市| 淳化县| 唐河县| 准格尔旗| 明星| 应用必备| 鄂尔多斯市| 通河县| 满城县| 通许县| 兴安县| 瓮安县| 定结县| 城市| 长葛市| 葫芦岛市| 长兴县| 巩留县| 固始县| 和林格尔县| 大化| 长汀县| 博乐市| 军事| 永丰县| 博野县| 涞水县| 青田县| 辉南县| 华宁县| 宽甸| 巫溪县| 永兴县| 连云港市| 闻喜县|