python爬蟲:模擬12306登錄

超級鷹:

#!/usr/bin/env python
# coding:utf-8

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()


def codecjy():
    chaojiying = Chaojiying_Client('tjtj', 'tangjian219', '902590')#用戶中心>>軟件ID 生成一個替換 96001                         用戶名        密碼        軟件id
    im = open('./code.png', 'rb').read()#本地圖片文件路徑 來替換 a.jpg 有時WIN系統須要//
    code=chaojiying.PostPic(im,9004)['pic_str']#1902 驗證碼類型  官方網站>>價格體系 3.4+版 print 後要加()
    return code

爬蟲程序:

from selenium import webdriver
from selenium.webdriver import ActionChains
from time import sleep
from PIL import Image #安裝PIL或者是Pillow
from CJY import Chaojiying_Client

#封裝一個識別驗證碼的函數
def transformCode(imgPath,imgType):
    chaojiying = Chaojiying_Client('超級鷹用戶名', '超級鷹密碼', '899370')
    im = open(imgPath, 'rb').read()
    return chaojiying.PostPic(im, imgType)['pic_str']


bro = webdriver.Chrome(executable_path='./chromedriver.exe')

bro.get('https://kyfw.12306.cn/otn/login/init')
sleep(2)
#將當前瀏覽器頁面進行圖片保存
bro.save_screenshot('./main.png')
#將驗證碼的局部區域進行裁剪
#捕獲標籤在頁面中的位置信息
img_tag = bro.find_element_by_xpath('//*[@id="loginForm"]/div/ul[2]/li[4]/div/div/div[3]/img')
location = img_tag.location#標籤的起始位置座標(左下角座標)
size = img_tag.size#標籤的尺寸
#裁剪範圍對應的矩形區域
rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']))
#使用Image工具進行指定區域的裁剪
i = Image.open('./main.png')
frame = i.crop(rangle)#crop就是根據指定的裁剪範圍進行圖片的截取
frame.save('code.png')

#調用打碼平臺進行驗證碼的識別
result = transformCode('./code.png',9004)
print(result) #x1,y1|x2,y2|x3,y3

#x1,y1|x2,y2|x3,y3 ==>[[x1,y1],[x2,y2],[x3,y3]]
all_list = []#[[x1,y1],[x2,y2],[x3,y3]]    驗證碼中圖片中的點擊內容的座標
if '|' in result:
    list_1 = result.split('|')
    count_1 = len(list_1)
    for i in range(count_1):
        xy_list = []
        x = int(list_1[i].split(',')[0])
        y = int(list_1[i].split(',')[1])
        xy_list.append(x)
        xy_list.append(y)
        all_list.append(xy_list)
else:
    x = int(result.split(',')[0])
    y = int(result.split(',')[1])
    xy_list = []
    xy_list.append(x)
    xy_list.append(y)
    all_list.append(xy_list)


for point in all_list:
    x = point[0]
    y = point[1]
    ActionChains(bro).move_to_element_with_offset(img_tag,x,y).click().perform()
    sleep(1)


bro.find_element_by_id('username').send_keys('xxxxxx')  #12306用戶名
sleep(1)
bro.find_element_by_id('password').send_keys('xxxx')   #密碼
sleep(1)

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

sleep(10)
print(bro.page_source)
bro.quit()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章