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) the else : # =============================================== ======================== # input picture image index number in accordance with the open identification codes, there may be a one, two, three image number, separated by a comma between the number # e.g. 2,4,6, indicating the first row of the second, fourth and sixth rows of the second sheet # ----------------- ---------------------- # | | | # 0 | 1 | 2 | 3 # | | | # ----------- ---------------------------- # | | | # 4 | 5 | 6 | 7 # | | | # ----- ---------------------------------- #================================================== ===================== input_index = iNPUT ( ' enter the security code location to "," split (e.g. 2,4,6): ' ) return input_index # check code DEF check_captcha (index): index_list = str (index) .split ( " , " ) # As the official verification code 12306 is to verify the correct code coordinate range, we take the midpoint of the coordinates of each code ( Approx.) 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 ' , # fixed ' RAND ' : ' sjrand ' , # fixed ' answer ' : right_position_str # codes corresponding to the center coordinates of the string ID } the try : Response = session.post (= check_captcha_url URL, Data = Data, = headers headers, Verify = False) the except the ConnectionError AS E: Print (E) the else : json_result = jsons.loads (response.content) Print (json_result) check_code = int (json_result [ ' RESULT_CODE ' ]) # remove verification results, 4: 5 Success: verification fails 7: expires IF check_code == 4 : Print (json_result [ ' result_message ' ]) return True elif check_code == 5 : Print (json_result [ ' result_message ' ]) the else : Print (json_result [ ' result_message ' ]) return False DEF main (): img_index = get_captcha_position() check_captcha(img_index) if __name__ == '__main__': main()
The results are shown: