幾種驗(yàn)證碼識別

了解更多關(guān)注微信公眾號“木下學(xué)Python”吧~
原文:https://blog.csdn.net/zjkpy_5/article/details/83472122

1.圖形驗(yàn)證碼

import pytesseract
from PIL import Image

im=Image.open('image.png')

轉(zhuǎn)化為灰度圖像

im = im.convert('L') #轉(zhuǎn)化為灰度圖像
threshold = 127
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)

im = im.point(table,'1')
print(pytesseract.image_to_string(im))

2.極驗(yàn)驗(yàn)證碼

import time
from io import BytesIO
from PIL import Image
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

EMAIL = '1347904922@qq.com'
PASSWORD = 'Zjk12345'
BORDER = 6
INIT_LEFT = 60

class CrackGeetest():
def init(self):
self.url = 'https://account.geetest.com/login'
self.browser = webdriver.Chrome()
self.wait = WebDriverWait(self.browser, 20)
self.email = EMAIL
self.password = PASSWORD

def __del__(self):
    self.browser.close()

def get_geetest_button(self):
    """
    獲取初始驗(yàn)證按鈕
    :return:
    """
    button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_radar_tip')))
    return button

def get_position(self):
    """
    獲取驗(yàn)證碼位置
    :return: 驗(yàn)證碼位置元組
    """
    img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))
    time.sleep(2)
    location = img.location
    size = img.size
    top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size[
        'width']
    return (top, bottom, left, right)

def get_screenshot(self):
    """
    獲取網(wǎng)頁截圖
    :return: 截圖對象
    """
    screenshot = self.browser.get_screenshot_as_png()
    screenshot = Image.open(BytesIO(screenshot))
    return screenshot

def get_slider(self):
    """
    獲取滑塊
    :return: 滑塊對象
    """
    slider = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_slider_button')))
    return slider

def get_geetest_image(self, name='captcha.png'):
    """
    獲取驗(yàn)證碼圖片
    :return: 圖片對象
    """
    top, bottom, left, right = self.get_position()
    print('驗(yàn)證碼位置', top, bottom, left, right)
    screenshot = self.get_screenshot()
    captcha = screenshot.crop((left, top, right, bottom))
    captcha.save(name)
    return captcha

def open(self):
    """
    打開網(wǎng)頁輸入用戶名密碼
    :return: None
    """
    self.browser.get(self.url)
    email = self.wait.until(EC.presence_of_element_located((By.ID, 'email')))
    password = self.wait.until(EC.presence_of_element_located((By.ID, 'password')))
    email.send_keys(self.email)
    password.send_keys(self.password)

def get_gap(self, image1, image2):
    """
    獲取缺口偏移量
    :param image1: 不帶缺口圖片
    :param image2: 帶缺口圖片
    :return:
    """
    left = 60
    for i in range(left, image1.size[0]):
        for j in range(image1.size[1]):
            if not self.is_pixel_equal(image1, image2, i, j):
                left = i
                return left
    return left

def is_pixel_equal(self, image1, image2, x, y):
    """
    判斷兩個(gè)像素是否相同
    :param image1: 圖片1
    :param image2: 圖片2
    :param x: 位置x
    :param y: 位置y
    :return: 像素是否相同
    """
    # 取兩個(gè)圖片的像素點(diǎn)
    pixel1 = image1.load()[x, y]
    pixel2 = image2.load()[x, y]
    threshold = 60
    if abs(pixel1[0] - pixel2[0]) < threshold and abs(pixel1[1] - pixel2[1]) < threshold and abs(
            pixel1[2] - pixel2[2]) < threshold:
        return True
    else:
        return False

def get_track(self, distance):
    """
    根據(jù)偏移量獲取移動軌跡
    :param distance: 偏移量
    :return: 移動軌跡
    """
    # 移動軌跡
    track = []
    # 當(dāng)前位移
    current = 0
    # 減速閾值
    mid = distance * 4 / 5
    # 計(jì)算間隔
    t = 0.2
    # 初速度
    v = 0

    while current < distance:
        if current < mid:
            # 加速度為正2
            a = 2
        else:
            # 加速度為負(fù)3
            a = -3
        # 初速度v0
        v0 = v
        # 當(dāng)前速度v = v0 + at
        v = v0 + a * t
        # 移動距離x = v0t + 1/2 * a * t^2
        move = v0 * t + 1 / 2 * a * t * t
        # 當(dāng)前位移
        current += move
        # 加入軌跡
        track.append(round(move))
    return track

def move_to_gap(self, slider, track):
    """
    拖動滑塊到缺口處
    :param slider: 滑塊
    :param track: 軌跡
    :return:
    """
    ActionChains(self.browser).click_and_hold(slider).perform()
    for x in track:
        ActionChains(self.browser).move_by_offset(xoffset=x, yoffset=0).perform()
    time.sleep(0.5)
    ActionChains(self.browser).release().perform()

def login(self):
    """
    登錄
    :return: None
    """
    submit = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'login-btn')))
    submit.click()
    time.sleep(10)
    print('登錄成功')

def crack(self):
    # 輸入用戶名密碼
    self.open()
    # 點(diǎn)擊驗(yàn)證按鈕
    button = self.get_geetest_button()
    button.click()
    # 獲取驗(yàn)證碼圖片
    image1 = self.get_geetest_image('captcha1.png')
    # 點(diǎn)按呼出缺口
    slider = self.get_slider()
    slider.click()
    # 獲取帶缺口的驗(yàn)證碼圖片
    image2 = self.get_geetest_image('captcha2.png')
    # 獲取缺口位置
    gap = self.get_gap(image1, image2)
    print('缺口位置', gap)
    # 減去缺口位移
    gap -= BORDER
    # 獲取移動軌跡
    track = self.get_track(gap)
    print('滑動軌跡', track)
    # 拖動滑塊
    self.move_to_gap(slider, track)

    success = self.wait.until(
        EC.text_to_be_present_in_element((By.CLASS_NAME, 'geetest_success_radar_tip_content'), '驗(yàn)證成功'))
    print(success)

    # 失敗后重試
    if not success:
        self.crack()
    else:
        self.login()

if name == 'main':
crack = CrackGeetest()
crack.crack()

3.微博宮格驗(yàn)證碼

import os
import time
from io import BytesIO
from PIL import Image
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from os import listdir

USERNAME = '15874295385'
PASSWORD = 'fpdpvx119'

TEMPLATES_FOLDER = 'templates/'

class CrackWeiboSlide():
def init(self):
self.url = 'https://passport.weibo.cn/signin/login?entry=mweibo&r=https://m.weibo.cn/'
self.browser = webdriver.Chrome()
self.wait = WebDriverWait(self.browser, 20)
self.username = USERNAME
self.password = PASSWORD

def __del__(self):
    self.browser.close()

def open(self):
    """
    打開網(wǎng)頁輸入用戶名密碼并點(diǎn)擊
    :return: None
    """
    self.browser.get(self.url)
    username = self.wait.until(EC.presence_of_element_located((By.ID, 'loginName')))
    password = self.wait.until(EC.presence_of_element_located((By.ID, 'loginPassword')))
    submit = self.wait.until(EC.element_to_be_clickable((By.ID, 'loginAction')))
    username.send_keys(self.username)
    password.send_keys(self.password)
    submit.click()

def get_position(self):
    """
    獲取驗(yàn)證碼位置
    :return: 驗(yàn)證碼位置元組
    """
    try:
        img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'patt-shadow')))
    except TimeoutException:
        print('未出現(xiàn)驗(yàn)證碼')
        self.open()
    time.sleep(2)
    location = img.location
    size = img.size
    top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size[
        'width']
    return (top, bottom, left, right)

def get_screenshot(self):
    """
    獲取網(wǎng)頁截圖
    :return: 截圖對象
    """
    screenshot = self.browser.get_screenshot_as_png()
    screenshot = Image.open(BytesIO(screenshot))
    return screenshot

def get_image(self, name='captcha.png'):
    """
    獲取驗(yàn)證碼圖片
    :return: 圖片對象
    """
    top, bottom, left, right = self.get_position()
    print('驗(yàn)證碼位置', top, bottom, left, right)
    screenshot = self.get_screenshot()
    captcha = screenshot.crop((left, top, right, bottom))
    captcha.save(name)
    return captcha

def is_pixel_equal(self, image1, image2, x, y):
    """
    判斷兩個(gè)像素是否相同
    :param image1: 圖片1
    :param image2: 圖片2
    :param x: 位置x
    :param y: 位置y
    :return: 像素是否相同
    """
    # 取兩個(gè)圖片的像素點(diǎn)
    pixel1 = image1.load()[x, y]
    pixel2 = image2.load()[x, y]
    threshold = 20
    if abs(pixel1[0] - pixel2[0]) < threshold and abs(pixel1[1] - pixel2[1]) < threshold and abs(
            pixel1[2] - pixel2[2]) < threshold:
        return True
    else:
        return False

def same_image(self, image, template):
    """
    識別相似驗(yàn)證碼
    :param image: 待識別驗(yàn)證碼
    :param template: 模板
    :return:
    """
    # 相似度閾值
    threshold = 0.99
    count = 0
    for x in range(image.width):
        for y in range(image.height):
            # 判斷像素是否相同
            if self.is_pixel_equal(image, template, x, y):
                count += 1
    result = float(count) / (image.width * image.height)
    if result > threshold:
        print('成功匹配')
        return True
    return False

def detect_image(self, image):
    """
    匹配圖片
    :param image: 圖片
    :return: 拖動順序
    """
    for template_name in listdir(TEMPLATES_FOLDER):
        print('正在匹配', template_name)
        template = Image.open(TEMPLATES_FOLDER + template_name)
        if self.same_image(image, template):
            # 返回順序
            numbers = [int(number) for number in list(template_name.split('.')[0])]
            print('拖動順序', numbers)
            return numbers

def move(self, numbers):
    """
    根據(jù)順序拖動
    :param numbers:
    :return:
    """
    # 獲得四個(gè)按點(diǎn)
    circles = self.browser.find_elements_by_css_selector('.patt-wrap .patt-circ')
    dx = dy = 0
    for index in range(4):
        circle = circles[numbers[index] - 1]
        # 如果是第一次循環(huán)
        if index == 0:
            # 點(diǎn)擊第一個(gè)按點(diǎn)
            ActionChains(self.browser) \
                .move_to_element_with_offset(circle, circle.size['width'] / 2, circle.size['height'] / 2) \
                .click_and_hold().perform()
        else:
            # 小幅移動次數(shù)
            times = 30
            # 拖動
            for i in range(times):
                ActionChains(self.browser).move_by_offset(dx / times, dy / times).perform()
                time.sleep(1 / times)
        # 如果是最后一次循環(huán)
        if index == 3:
            # 松開鼠標(biāo)
            ActionChains(self.browser).release().perform()
        else:
            # 計(jì)算下一次偏移
            dx = circles[numbers[index + 1] - 1].location['x'] - circle.location['x']
            dy = circles[numbers[index + 1] - 1].location['y'] - circle.location['y']

def crack(self):
    """
    破解入口
    :return:
    """
    self.open()
    # 獲取驗(yàn)證碼圖片
    image = self.get_image('captcha.png')
    numbers = self.detect_image(image)
    self.move(numbers)
    time.sleep(10)
    print('識別結(jié)束')

if name == 'main':
crack = CrackWeiboSlide()
crack.crack()

4.超級鷹接口驗(yàn)證碼

import requests
from hashlib import md5

class Chaojiying(object):

def __init__(self, username, password, soft_id):
    self.username = username
    self.password = md5(password.encode('utf-8')).hexdigest()
    self.soft_id = soft_id
    self.base_params = {
        'user': self.username,
        'pass2': self.password,
        'softid': self.soft_id,
    }
    self.headers = {
        'Connection': 'Keep-Alive',
        'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
    }

def post_pic(self, im, codetype):
    """
    im: 圖片字節(jié)
    codetype: 題目類型 參考 http://www.chaojiying.com/price.html
    """
    params = {
        'codetype': codetype,
    }
    params.update(self.base_params)
    files = {'userfile': ('ccc.jpg', im)}
    r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files,
                      headers=self.headers)
    return r.json()

def report_error(self, im_id):
    """
    im_id:報(bào)錯(cuò)題目的圖片ID
    """
    params = {
        'id': im_id,
    }
    params.update(self.base_params)
    r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
    return r.json()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末结蟋,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌隘蝎,老刑警劉巖痛单,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件撰茎,死亡現(xiàn)場離奇詭異淳附,居然都是意外死亡搂妻,警方通過查閱死者的電腦和手機(jī)蒙保,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來欲主,“玉大人邓厕,你說我怎么就攤上這事”馄埃” “怎么了详恼?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長引几。 經(jīng)常有香客問我昧互,道長,這世上最難降的妖魔是什么伟桅? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任敞掘,我火速辦了婚禮,結(jié)果婚禮上楣铁,老公的妹妹穿的比我還像新娘玖雁。我一直安慰自己,他們只是感情好盖腕,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布赫冬。 她就那樣靜靜地躺著浓镜,像睡著了一般。 火紅的嫁衣襯著肌膚如雪劲厌。 梳的紋絲不亂的頭發(fā)上竖哩,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天,我揣著相機(jī)與錄音脊僚,去河邊找鬼。 笑死遵绰,一個(gè)胖子當(dāng)著我的面吹牛辽幌,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播椿访,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼乌企,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了成玫?” 一聲冷哼從身側(cè)響起加酵,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎哭当,沒想到半個(gè)月后猪腕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡钦勘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年陋葡,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片彻采。...
    茶點(diǎn)故事閱讀 40,498評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡腐缤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出肛响,到底是詐尸還是另有隱情岭粤,我是刑警寧澤,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布特笋,位于F島的核電站剃浇,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏雹有。R本人自食惡果不足惜偿渡,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望霸奕。 院中可真熱鬧溜宽,春花似錦、人聲如沸质帅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至嫉嘀,卻和暖如春炼邀,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背剪侮。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工拭宁, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人瓣俯。 一個(gè)月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓杰标,卻偏偏與公主長得像,于是被迫代替她去往敵國和親彩匕。 傳聞我的和親對象是個(gè)殘疾皇子腔剂,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 驗(yàn)證碼的另一種方法:極驗(yàn)驗(yàn)證碼, 此文章代碼非原創(chuàng)驼仪,如有侵權(quán)掸犬,請告知?jiǎng)h除。 我們以bilibili為例:https...
    煎煉閱讀 1,514評論 0 0
  • 我們可以借助插件來做 打開插件绪爸,找到自己需要的驗(yàn)證碼 篩選有用的路徑 把對應(yīng)的視圖函數(shù)也拿過來湾碎,注意還需要一個(gè)ge...
    程序員之路閱讀 1,337評論 0 1
  • selenium用法詳解 selenium主要是用來做自動化測試,支持多種瀏覽器奠货,爬蟲中主要用來解決JavaScr...
    陳_CHEN_陳閱讀 3,904評論 1 5
  • 前言 離上一篇更新的博文應(yīng)該過了挺久的了(python爬蟲(上)–請求——關(guān)于旅游網(wǎng)站的酒店評論爬仁ぜ搿(傳參方法))...
    Mrhyden閱讀 514評論 0 0
  • 愛笑的女生運(yùn)氣不會太差 總聽人這么說 今年24歲的我 在我過往的二十四年里 也算見過形形色色的笑容 有一種人是骨子...
    不懂事的大人閱讀 261評論 0 1