Python 之12306網站驗證碼校驗案例


import requests
from PIL import Image
import jsons

requests.packages.urllib3.disable_warnings()

headers = {
    "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}
session = requests.session()


# 獲取驗證碼位置
def get_captcha_position(img_name="12303_captcha.png"):
    url = "https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand";
    try:
        response = session.get(url=url, headers=headers, verify=False)
    except ConnectionError as e:
        print(e)
    else:
        with open(img_name, "wb") as f:
            f.write(response.content)
        try:
            # 人眼查看驗證碼
            with Image.open(img_name) as img:
                img.show()
        except FileNotFoundError as e:
            print(e)
        else:
            # =======================================================================
            # 根據打開的圖片識別驗證碼輸入圖片索引序號,有可以是1張、2張、3張圖片的序號,序號之間用逗號隔開
            # 例如2,4,6,表示第1排第2,第2排第4,6張
            # ---------------------------------------
            #         |         |         |
            #    0    |    1    |    2    |     3
            #         |         |         |
            # ---------------------------------------
            #         |         |         |
            #    4    |    5    |    6    |     7
            #         |         |         |
            # ---------------------------------------
            # =======================================================================
            input_index = input('請輸入驗證碼位置,以","分割(例如2,4,6):')
            return input_index


# 校驗驗證碼
def check_captcha(index):
    index_list = str(index).split(",")
    # 由於12306官方驗證碼是驗證正確驗證碼的坐標范圍,我們取每個驗證碼中點的坐標(大約值)
    img_center_position = ['35,35', '105,35', '175,35', '245,35', '35,105', '105,105', '175,105', '245,105']
    right_position = []
    for i in index_list:
        right_position.append(img_center_position[int(i)])
    right_position_str = ",".join(right_position)
    check_captcha_url = "https://kyfw.12306.cn/passport/captcha/captcha-check"
    data = {
        'login_site': 'E',  # 固定的
        'rand': 'sjrand',  # 固定的
        'answer': right_position_str  # 驗證碼對應的中心坐標字符串序號
    }
    try:
        response = session.post(url=check_captcha_url, data=data, headers=headers, verify=False)
    except ConnectionError as e:
        print(e)
    else:
        json_result = jsons.loads(response.content)
        print(json_result)
        check_code = int(json_result['result_code'])
        # 取出驗證結果,4:成功  5:驗證失敗  7:過期
        if check_code == 4:
            print(json_result['result_message'])
            return True
        elif check_code == 5:
            print(json_result['result_message'])
        else:
            print(json_result['result_message'])
        return False


def main():
    img_index = get_captcha_position()
    check_captcha(img_index)


if __name__ == '__main__':
    main()

結果如圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM