溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python如何實現(xiàn)自動登錄12306并自動點擊驗證碼完成登錄

發(fā)布時間:2021-08-07 09:33:41 來源:億速云 閱讀:517 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹python如何實現(xiàn)自動登錄12306并自動點擊驗證碼完成登錄,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

以下代碼可自動登錄12306 - 包括輸入用戶名密碼以及自動識別驗證碼并點擊驗證碼登陸。該源碼需要稍作修改:

把  username.send_keys('xxxxxxx')  中的  xxxxxx 改為 你自己的12306賬號。

把  password.send_keys('yyyyyy')     中的 yyyyy 改為自己的 12306 密碼。

即可運行。

該源碼把自動搶票的核心功能:識別驗證碼并點擊驗證碼登陸實現(xiàn)了。

把代碼稍作加工,即可變?yōu)樽约旱淖詣訐屍贝a。

運行環(huán)境 - 需要安裝python運行環(huán)境,selenium,requests,瀏覽器默認為chrome。

運行時 程序會自動分析并識別驗證碼并點擊驗證碼,完成登陸過程。。。

詳細代碼如下:

#12306 自動打開12306網(wǎng)站,并輸入用戶名、密碼和驗證碼,并登錄12306,
#author bigluo
#email: 3490699170@qq.com
#coding=utf-8
from selenium import webdriver
import time
from PIL import Image
from selenium.webdriver.common.action_chains import ActionChains
import os
import requests
import numpy
#指定button id和button文本值,并點擊,連續(xù)點擊5次
#return:
#0 click successfully
#-1 連續(xù)5次均failed
#1 txt != dest_text,所以不點擊
def click_button(b,id,dest_text,j):  #在當前頁面查找并點擊指定text,錯誤返回 -1.連續(xù)5次,錯誤時延時1秒
 txt=''
 for i in range(0,5):
  try:
   txt=b.find_element_by_id(id).text
   if txt == dest_text:
    b.find_element_by_id(id).click()
    return 0 
   else:
    return 1
  except:
   time.sleep(1)
   continue
 return -1       #5次都失敗了
#給定button id和text,find a given text
#0 found
#-1 not found
def find_button(b,id,dest_text):
 txt=''
 try:
   txt=b.find_element_by_id(id).text
   if txt == dest_text:
    return 0
 except:  
   #print("find_button Error --page txt is "+txt+" input text is "+dest_text)
   return -1
 return -1
#click refresh pic button
def click_refresh(b):
 try:
  b.find_element_by_xpath("//*[@id='loginForm']/div/ul[2]/li[4]/div/div/div[1]").click()
 except:
  print("click_refresh:exception!!!!")
#初始化瀏覽器 
def init_browser(b):
 b.maximize_window()
#進入登錄頁,必須是未登錄狀態(tài)
# 0 : 成功
#-1 : 出錯了
def visit_login_page(b):
 url = 'https://kyfw.12306.cn/otn/index/init'
 b.get(url)
 if find_button(b,u"login_user",u"登錄") != 0: #沒退出
  click_button(b,u"regist_out",u"退出",0)  #點擊退出
  time.sleep(5)         #休息5秒再查看是否退出
 if click_button(b,u"login_user",u"登錄",0) != 0: #點擊登陸按鈕
  return -1     #Error happened!!
 time.sleep(10)     #訪問login page后休息10秒,等待驗證碼圖片加載完成 
 return 0
#截取一張驗證碼圖片,保存為aa.png
def get_a_verify_pic(b):
 imgelement=b.find_element_by_xpath("//*[@id='loginForm']/div/ul[2]/li[4]/div/div/div[3]")
 location = imgelement.location #獲取驗證碼x,y軸坐標 
 size=imgelement.size #獲取驗證碼的長寬
 rangle=(int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height'])) #寫成我們需要截取的位置坐標
 b.save_screenshot('aa.png')
 i=Image.open("aa.png") #打開截圖
 pic_name='verify_code'+".jpg" #標準12306驗證圖片
 frame4=i.crop(rangle) #使用Image的crop函數(shù),從截圖中再次截取我們需要的區(qū)域
 frame4.save(pic_name)
 return pic_name
#破解圖片驗證碼
def ana_pic(b,pic_name):
 body_list=[]
 url='''http://littlebigluo.qicp.net:47720/'''
 files={'file':(pic_name,open(pic_name,'rb'),'image/png')}
 res=requests.post(url,files=files)    #post pic
 if res.status_code == 200:      #return ok
  try:
   #print(res.text)
   if u"文字應(yīng)該" in res.text:    #識別驗證碼成功    
    body_str_1=res.text.split(u'''<B>''')
    body_str=body_str_1[2].split(u'<')[0].split()   
    for index in body_str:
     body_list.append(int(index))
    return 0,numpy.array(body_list)
  except:
   print("ana pic failed!!!!")
   return -1,None
 return -1,None     #驗證碼解析失敗
#按輸入的下標,點擊一張驗證碼圖片
def click_one_pic(b,i):
 try:
  imgelement=b.find_element_by_xpath("//*[@id='loginForm']/div/ul[2]/li[4]/div/div/div[3]")
  if i<=4:
   ActionChains(b).move_to_element_with_offset(imgelement,40+72*(i-1),73).click().perform()
  else:
   i -= 4
   ActionChains(b).move_to_element_with_offset(imgelement,40+72*(i-1),145).click().perform()
 except:
  print("Wa -- click one pic except!!!")
#按bodylist 指示,點擊指定驗證圖片
def click_pic(b,body_list):
 for i in range(len(body_list)):
  click_one_pic(b,body_list[i])
  time.sleep(1)
#輸入用戶名密碼,并點擊驗證碼登陸
#0:login successfully
#1:verify code failed,
#-1 error happened
def login(b):
 pic_name=None
 try:
  pic_name=get_a_verify_pic(b)   #截取12306驗證碼圖片
  ret_val,body_list=ana_pic(b,pic_name) #破解12306驗證碼
  username=b.find_element_by_id('username')
  username.clear()
  username.send_keys('xxxxxx')
  password=b.find_element_by_id('password')
  password.clear()
  password.send_keys('yyyyyyy') 
  time.sleep(2) 
  if ret_val != 0:
   #print("login : what??? predict return error!!")
   print("login -- no verified pic!!! !!")
   os.remove(pic_name)    #exception occured
   #click_refresh(b)
   return -1
  if len(body_list) == 0:    #no pic recognized
   click_refresh(b)
   print("login : what??? body list is null!!!")
   os.remove(pic_name)    #exception occured
   return 1      #verified failed
  click_pic(b,body_list)
  time.sleep(1)      #休息1秒再點擊登陸按鈕
  if click_button(b,u"loginSub",u"登錄",0) != 0:
   print("login : what??? click button exception!!!")
   return -1     #Error happened!! 
 except:
  if None != pic_name:
   os.remove(pic_name)    #exception occured
  print("login:exception!!")
  return -1
 time.sleep(5)      #查看驗證碼是否正確??
 ret_val=find_button(b,u"error_msgmypasscode1",u"請點擊正確的驗證碼")
 if ret_val == 0:     #驗證碼錯誤
  print("login--Verified code error!!!")
  return 1
 os.remove(pic_name)
 print("login--successfully!!!")
 return 0
#循環(huán)login
#返回
#0:登陸成功-正常返回
#-1:登陸失敗或異常返回
#1 :驗證碼未識別出來
def try_login(b):
 for k in range(0,5):     #連續(xù)嘗試5次
  rt_val=login(b)
  if rt_val < 0:      #error happened
   print("verify got exception!!")
   time.sleep(10)
   continue
  elif rt_val == 1:     #verified code error
   print("verify - code error!!")
   time.sleep(5)
   continue      #login again
  else:        #login successfully
   print("login successfully!!!")
   return 0    
 return -1     #login failed
if __name__ == "__main__": 
 b = webdriver.Chrome()
 init_browser(b)
 visit_login_page(b)
 ret_val = try_login(b) #嘗試登錄
 if ret_val<0:  
  print("main -- try_login failed!!!") 
 else:
  print("main -- try_login successfully!!!") 
 print("Good job!bigluo??!")

以上是“python如何實現(xiàn)自動登錄12306并自動點擊驗證碼完成登錄”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI