什么是圖片驗證碼?
驗證碼(CAPTCHA)是"Completely Automated Public Turing test to tell Computers and HumansApart”(全自動區分計算機和人類的圖靈測試)的縮寫,是一種區分用戶是計算機還是人的公共全自動程序。
圖片驗證碼的處理方案
- 手動輸入(input)這種方法僅限于登錄一次就可持續使用的情況
- 圖像識別引擎解析使用光學識別引擎處理圖片中的數據,目前常用于圖片數據提取,較少用于驗證碼處理
- 打碼平臺爬蟲常用的驗證碼解決方案
圖片識別引擎
OCR(Optical Character Recognition)是指使用掃描儀或數碼相機對文本資料進行掃描成圖像文件,然后對圖像文件進行分析處理,自動識別獲取文字信息及版面信息的軟件。
什么是tesseract
Tesseract,一款由HP實驗室開發由Google維護的開源OCR引擎,特點是開源,免費,支持多語言,多
平臺。
項目地址:https:/github.com/tesseract-ocr/tesseract
圖片識別引擎環境的安裝
-mac環境下直接執行命令:brew install --with-training-tools tesseract
-windows環境下的安裝可以通過exe安裝包安裝,下載地址:Home · UB-Mannheim/tesseract Wiki · GitHub
安裝完成后記得將Tesseract 執行文件的目錄加入到PATH中,方便后續調用。
配置教程:超詳細解決pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it’s not in yo… - 簡書 (jianshu.com)
- 從第5步開始看
- 其中第9步的修改py文件的文件路徑在報錯里可以找到(這個報錯在下面的"使用代碼"執行后可以得到)
- 當然,如果配置成功就沒有報錯了
-linux環境下的安裝:sudo apt-get install tesseract-ocr
Python庫的安裝
# PIL用于打開圖片文件
pip install pillow
# pytesseract模塊用于從圖片中解析數據
pip install pytesseract
使用代碼
# 圖像識別引擎
from PIL import Image
import pytesseractim = Image.open("圖片路徑")
result = pytesseract.image_to_string(im)
print(result)
其他OCR平臺
微軟Azure 圖像識別:https://azure.microsoft.com/zh-cn/services/cognitive-services/computer-vision/
阿里云圖文識別:https://www.aliyun.com/product/cdi/
騰訊OCR文字識別:https://cloud.tencent.com/product/ocr
國內的識別引擎對于中文的支持會更好
常見的驗證碼的種類
url地址不變,驗證碼不變
這是驗證碼里面非常簡單的一種類型,對應的只需要獲取驗證碼的地址,然后請求,通過打碼平臺識別即可
url地址不變,驗證碼變化
這種驗證碼的類型是更加常見的一種類型,對于這種驗證碼,大家需要思考:在登錄的過程中,假設我輸入的驗證碼是對的,對方服務器是如何判斷當前我輸入的驗證碼是顯示在我屏幕上的驗證碼,而不是其他的驗證碼呢?
在獲取網頁的時候,請求驗證碼,以及提交驗證碼的時候,對方服務器肯定通過了某種手段驗證我之前獲取的驗證碼和最后提交的驗證碼是同一個驗證碼,那這個手段是什么手段呢?
很明顯,就是通過cookie來實現的,所以對應的,在請求頁面,請求驗證碼,提交驗證碼的到時候需要保證cookie的一致性,對此可以使用requests.session來解決
打碼平臺——2Captcha的使用
筆者自己使用的,需要付費;可自行使用其他平臺
網址:https://2captcha.com/zh
以下教程來源:Python驗證碼破解程序——在線識別驗證碼和2Captcha的Anti Captcha API
pip3 install 2captcha-python
TwoCaptcha
類實例可按照如下方法創建:
from twocaptcha import TwoCaptchasolver = TwoCaptcha('YOUR_API_KEY')
# 您還能為已創建的實例設置選項:
config = {'server': '2captcha.com','apiKey': 'YOUR_API_KEY','softId': 123,'callback': 'https://your.site/result-receiver','defaultTimeout': 120,'recaptchaTimeout': 600,'pollingInterval': 10,}
solver = TwoCaptcha(**config)
實例選項
選項 | 默認值 | 說明 |
---|---|---|
服務器 | ‘2captcha.com’ | API服務器。您可以將注冊賬戶設置為‘rucaptcha.com’。 |
softId | - | 您將在2Captcha軟件目錄發布后獲得軟件ID |
回調函數 | - | 驗證碼識別結果會發送至網絡服務器URL,但應先在賬戶的pingback設置中注冊URL |
defaultTimeout | 120 | 除reCAPTCHA外的驗證碼的輪詢超時時間(秒),用于判定模塊嘗試從res.php API端點獲得答案的時間 |
recaptchaTimeout | 600 | reCAPTCHA的輪詢超時時間(秒),用于判定模塊嘗試從res.php API端點獲得答案的時間 |
pollingInterval | 10 | 向res.php API端點發送請求的間隔時間(秒),不建議設置在5秒以內 |
重要提示:一旦回調函數
確定用于TwoCaptcha
實例,那么所有方法都只返回驗證碼ID,無法通過輪詢API獲得結果。結果將發送至回調URL。請通過getResult方法進行人工破解。
您在提交圖片驗證碼時可提出額外選項,以便2Captcha的員工能夠正確破解。
驗證碼選項
選項 | 默認值 | 說明 |
---|---|---|
numeric | 0 | 判定驗證碼是否由數字或其他符號組成,詳情請見API文檔。 |
minLength | 0 | 最小答案長度 |
maxLength | 0 | 最大答案長度 |
phrase | 0 | 判定答案是否由多個詞語組成 |
caseSensitive | 0 | 判定答案是否區分大小寫 |
calc | 0 | 確定驗證碼需要計算 |
lang | - | 確定驗證碼語言,見可用語言列表。 |
hintImg | - | 所有驗證碼員工可見的提示圖片 |
hintText | - | 員工可見的驗證碼提示或任務文字 |
驗證碼類別
您可以利用以下方法繞過normal captcha(帶有扭曲文字的圖片)。這個方法也可用于識別圖片上的任何文字。
result = solver.normal('path/to/captcha.jpg', param1=..., ...)
這種方法可用于繞過需要回答清晰文字問題的驗證碼。
result = solver.text('If tomorrow is Saturday, what day is today?', param1=..., ...)
此方法可破解reCAPTCHA V2,并獲得令牌實現繞過保護。
result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',url='https://mysite.com/page/with/recaptcha',param1=..., ...)
此方法利可破解reCAPTCHA V3,并返回令牌。
result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',url='https://mysite.com/page/with/recaptcha',version='v3',param1=..., ...)
FunCaptcha(Arkoselabs)破解方法,并返回令牌。
result = solver.funcaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',url='https://mysite.com/page/with/funcaptcha',param1=..., ...)
此方法可破解GeeTest拼圖驗證碼,并返回一組JSON格式的令牌。
result = solver.geetest(gt='f1ab2cdefa3456789012345b6c78d90e',challenge='12345678abc90123d45678ef90123a456b',url='https://www.site.com/page/',param1=..., ...)
此方法可破解hCaptcha,并返回可以繞過驗證碼的令牌。
result = solver.hcaptcha(sitekey='10000000-ffff-ffff-ffff-000000000001',url='https://www.site.com/page/', param1=..., ...)
通過令牌形式破解KeyCaptcha。
result = solver.keycaptcha(s_s_c_user_id=10,s_s_c_session_id='493e52c37c10c2bcdf4a00cbc9ccd1e8',s_s_c_web_server_sign='9006dc725760858e4c0715b835472f22-pz-',s_s_c_web_server_sign2='2ca3abe86d90c6142d5571db98af6714',url='https://www.keycaptcha.ru/demo-magnetic/', param1=..., ...)
以令牌形式繞過Capy拼圖驗證碼。
result = solver.capy(sitekey='PUZZLE_Abc1dEFghIJKLM2no34P56q7rStu8v',url='http://mysite.com/',api_server='https://jp.api.capy.me/',param1=..., ...)
Grid法最初名為Old reCAPTCHA V2法,先在圖中畫好網格,點擊特定網格框,以繞過任何類型的驗證碼。這種方法會返回方框數。
result = solver.grid('path/to/captcha.jpg', param1=..., ...)
Canvas法需要圍著圖中物體畫一條線。這種方法會返回一組點坐標,用于繪制多邊形。
result = solver.canvas('path/to/captcha.jpg', param1=..., ...)
ClickCaptcha會返回驗證碼圖片的點坐標,若您需要點擊圖片的特定點,就可以使用這種方法。
result = solver.coordinates('path/to/captcha.jpg', param1=..., ...)
這種方法可破解需要旋轉物體的驗證碼,主要用于繞過FunCaptcha。它會返回旋轉角度。
result = solver.rotate('path/to/captcha.jpg', param1=..., ...)
一些方法&&操作
send / getResult
上述方法可用于人工提交驗證碼和答案輪詢。
import time
. . . . . id = solver.send(file='path/to/captcha.jpg')
time.sleep(20)code = solver.get_result(id)
balance
以此方法獲取賬戶余額:balance = solver.balance()
report
以此方法報告驗證碼答案之優劣。
solver.report(id, True) # captcha solved correctly
solver.report(id, False) # captcha solved incorrectly
如發生錯誤,驗證碼破解程序會提示異常。妥善處理這類情況很重要。我們推薦使用try/except
來處理異常。
Try:result = solver.text('If tomorrow is Saturday, what day is today?')
Except ValidationException as e:# invalid parameters passedprint(e)
Except NetworkException as e:# network error occurredprint(e)
Except ApiException as e:# api respond with errorprint(e)
Except TimeoutException as e:# captcha is not solved so farprint(e)
代理
您可以將代理作為參數應用于以下方法:recaptcha、funcaptcha、geetest。代理將被轉發至API以破解驗證碼。
proxy={'type': 'HTTPS','uri': 'login:password@IP_address:PORT'
}
異步回調
您也可以利用asyncio進行異步回調。
import asyncio
import concurrent.futures
from twocaptcha import TwoCaptchacaptcha_result = await captchaSolver(image)async def captchaSolver(image):loop = asyncio.get_running_loop()with concurrent.future.ThreadPoolExecutor() as pool:result = await loop.run_in_executor(pool, lambda: TwoCaptcha(API_KEY).normal(image))return result
使用selenium
完整教程請看:Selenium驗證碼求解器:如何使用反驗證碼2Captcha服務自動繞過reCAPTCHA、hCaptcha、Cloudflare、Arkose labs以及任何驗證碼
from selenium.webdriver.common.by import By
from twocaptcha import TwoCaptcha
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver# 實例化 WebDriver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))# 加載目標頁面
captcha_page_url = "https://recaptcha-demo.appspot.com/recaptcha-v2-checkbox.php"
driver.get(captcha_page_url)# 解決驗證碼問題
print("Solving Captcha")
solver = TwoCaptcha("2CAPTCHA_API_KEY")
response = solver.recaptcha(sitekey='SITE_KEY', url=captcha_page_url)
代碼 = response['code']
print(f "Successfully solved the Captcha. The solve code is {code}")# 設置已解決的驗證碼
recaptcha_response_element = driver.find_element(By.ID, 'g-recaptcha-response')
driver.execute_script(f'arguments[0].value = "{code}";', recaptcha_response_element)# 提交表單
submit_btn = driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]')
submit_btn.click()# 暫停執行,以便在關閉驅動程序前查看提交后的屏幕情況
輸入("按回車鍵繼續")
driver.close()
將 2CAPTCHA_API_KEY
和 SITE_KEY
替換為它們的值,然后運行代碼,驗證碼將被破解,你將看到成功界面。
簡單示例
from twocaptcha import TwoCaptcha
import timesolver = TwoCaptcha('your own key')
config = {'server': '2captcha.com','apiKey': 'your own key','defaultTimeout': 120,'recaptchaTimeout': 600,'pollingInterval': 10,}
solver = TwoCaptcha(**config)
result = solver.normal('captcha.jpg', caseSensitive=1)
id = solver.send(file='captcha.jpg')
time.sleep(20)
code = solver.get_result(id)
print(code)