模擬登陸 12306網站


模擬登陸 12306網站

准備

目標網站 :https://kyfw.12306.cn/otn/login/init
安裝PIL模塊: pip3 install pillow 或 pip3 --default-timeout=100 install -U pillow 第三方圖像處理庫(圖片定位裁剪)
准備一個瀏覽器驅動(版本不要差太多) chromedriver.exe  下載:https://npm.taobao.org/mirrors/chromedriver/
驗證碼識別網站(超級鷹):http://www.chaojiying.com/ 需要注冊,使用方法 參考#頁面中驗證碼識別;https://www.cnblogs.com/guokaifeng/p/11536706.html

需求分析

通過selenium模塊來實現模擬登錄
- 難點:對驗證碼的自動識別(驗證碼要一次獲取,刷新的話會更改驗證碼)
- 解決方案:對驗證碼區域進行截取(使用PIL模塊的Image),用超級鷹來獲取正確驗證碼的坐標,然后由selenium實現登錄    

實現代碼 (此代碼僅供學習參考,請勿非法使用)

from PIL import Image #導入Image截圖
from time import sleep 
from selenium import webdriver
from Cjy import Chaojiying_Client # 導入超級鷹驗證碼識別
from selenium.webdriver import ActionChains # 導入ActionChains動作鏈
bro = webdriver.Chrome(executable_path='chromedriver.exe') # 指定瀏覽器驅動
bro.get('https://kyfw.12306.cn/otn/login/init')
sleep(3) # 防止網絡(慢)原因圖片加載失敗

bro.find_element_by_id('username').send_keys('123456') # 輸入12306賬戶
bro.find_element_by_id('password').send_keys('67890000000') # 輸入密碼

bro.save_screenshot('main.png') # 截取顯示頁面

# 對頁面中的驗證碼圖片做定位
code_img_tag = bro.find_element_by_xpath('//*[@id="loginForm"]/div/ul[2]/li[4]/div/div/div[3]/img') # 定位到驗證碼圖片的標簽
location = code_img_tag.location # 圖片坐標(左下,右上) {'x':274,'y':293}
size = code_img_tag.size # 圖片的寬高 {'height':190,'width':293}
# 裁剪的區域范圍 (獲取驗證碼的圖片)
rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']))

# 使用Image裁剪出驗證碼圖片 code.png
i = Image.open('./main.png')
frame = i.crop(rangle)
frame.save('code.png')

# 調用超級鷹對圖片進行識別
def get_text(imgPath,imgType):
    chaojiying = Chaojiying_Client('賬戶', '密碼', '軟件id')#超級鷹的賬戶密碼軟件碼 注意最少要充1元才能使用
    im = open(imgPath, 'rb').read()
    return chaojiying.PostPic(im, imgType)['pic_str']

result = get_text('./code.png',9004) # 傳入驗證碼與驗證碼類型  返回值為正確圖片的坐標55,70|267,133 (賬戶不對或沒有余額 會報錯)

# 把圖片坐標轉換為 55,70|267,133 ==[[55,70],[267,133]]
all_list = []
lis = result.split('|')   #['55,70', '267,133']
all_list.append([int(a) for a in lis[0].split(',')])
all_list.append([int(a) for a in lis[-1].split(',')])
# 讓動作鏈去指定驗證碼區域模擬鼠標點擊
for a in all_list:
    x = a[0]
    y = a[1]
    ActionChains(bro).move_to_element_with_offset(code_img_tag,x,y).click().perform()
    sleep(1)


bro.find_element_by_id('loginSub').click() # 點擊登錄

sleep(5)
bro.quit() #退出


# 超級鷹代碼    
import requests
from hashlib import md5

class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode('utf8')
        self.password = md5(password).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 PostPic(self, im, codetype):
        """
        im: 圖片字節
        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 ReportError(self, im_id):
        """
        im_id:報錯題目的圖片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()    

作 者: 郭楷豐
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角 推薦一下。您的鼓勵是博主的最大動力!
自 勉:生活,需要追求;夢想,需要堅持;生命,需要珍惜;但人生的路上,更需要堅強。 帶着感恩的心啟程,學會愛,愛父母,愛自己,愛朋友,愛他人。


免責聲明!

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



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