模擬登入12306(selenium+超級鷹)
阿新 • • 發佈:2021-01-24
最近迷上了用selenium去登陸各大網站,別說selenium真挺好用,可以輕鬆搞定ajax動態載入的網頁,不用很費勁的去抓包查詢。咳咳…跑題了,迴歸正題。
這次用selenium去登入12306網站,聽說比較困難。我就去試了試,發現它的驗證碼實在是那啥…就是這樣的。聽頭疼的。
我來說說主要的程式碼編寫吧。
過程:
- 用我們的開發者工具定位到輸入賬號和密碼的視窗,找到並send_keys
driver.find_element_by_id('username').send_keys('使用者名稱')
time.sleep(0.5)
driver.find_element_by_id('password' ).send_keys('密碼')
- 然後複雜的過程就來了。我們想要得到驗證碼的圖片。但是頭疼的是,圖片是再變化的。我們請求一次,就變化一次,不像其他普通網站一樣不會變化,直接儲存圖片就行了。但是這是12306誒,哪這麼輕鬆。想了想,我決定把整張頁面截圖儲存下來,然後對驗證碼區域裁剪下來,就可以保證一致了。
# 將頁面進行截圖並儲存
driver.save_screenshot('12306登入頁面截圖.png')
# 確定驗證碼左上角和右下角的座標
code_img = driver.find_element_by_xpath('//*[@id="loginForm"]/div/ul[2]/li[4]/div/div/div[3]/img' )
location = code_img.location # 確定驗證碼圖片左上角的座標
print('location:', location)
size = code_img.size # 確定驗證碼圖片的長和寬
print('size:', size)
rangle = (int(location['x']), int(location['y']), int(location['x']) + int(size['width']),
int(location['y']) + int(size['height']))
print('rangle:', rangle)
i = Image.open('12306頁面截圖.png')
# 對指定區域裁剪
code_pic = i.crop(rangle)
file_name = 'code_pic.png'
code_pic.save(file_name)
time.sleep(2)
print('驗證碼圖片儲存成功!!')
- 我們識別驗證碼用的是超級鷹,具體如何使用可以去查一查。驗證碼有可能需要我們點選多個,所以通過打碼平臺會得到多個座標,就比如這種。有兩個日曆,需要點選兩次,通過超級鷹就會得到兩個座標。如下圖。我們發現有兩個座標會有一個“|”,有三個座標就有兩個“|”,所以我們就把他們split下,讓每個座標巢狀再一個列表裡。此過程程式碼如下:
# 識別驗證座標
chaojiying = Chaojiying_Client('使用者賬號', '密碼', '開發者賬號') # 使用者中心>>軟體ID 生成一個替換 96001
im = open('code_pic.png', 'rb').read() # 本地圖片檔案路徑 來替換 a.jpg 有時WIN系統須要//
result = chaojiying.PostPic(im, 9004)['pic_str'] # 1902 驗證碼型別 官方網站>>價格體系 3.4+版 print 後要加()
all_list = [] # 儲存被點選的座標
if '|' in result:
list1 = result.split('|')
xy_list = []
count1 = len(list1)
for i in list1:
x = int(list1[i].split(',')[0])
xy_list.append(x)
y = int(list1[i].split(',')[1])
xy_list.append(y)
all_list.append(xy_list)
else:
xy_list = []
x = int(result.split(',')[0])
xy_list.append(x)
y = int(result.split(',')[1])
xy_list.append(y)
all_list.append(xy_list)
print(all_list)
- 最後嘛,我們得到了驗證碼的座標,當然就去點選啦。但是,這個座標是相對於驗證碼的圖片的座標,我們必須用ActionChains來移動一下動作鏈的位置。把他移動到驗證碼圖片的location。,然後點選就ok了。此步驟的程式碼如下:
# 迴圈遍歷點選圖片
for i in all_list:
x = i[0]
y = i[1]
action = ActionChains(driver).move_to_element_with_offset(code_img, x, y).click().perform()
time.sleep(1)
driver.find_element_by_id('loginSub').click()
最後來看看全部程式碼吧!!
這個程式碼是超級鷹提供的介面。我封裝成一個類了。
#!/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()
下面是自己寫的,也就六七十行。
from selenium import webdriver
from chaojiying_Python.chaojiying import Chaojiying_Client
import time
from PIL import Image
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
# 實現無視覺化介面的操作
# chrome_options = Options()
# chrome_options.add_argument('--headless')
# chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome('D:\software\studySoftware\chromedriver_win32\chromedriver.exe')
driver.get('https://kyfw.12306.cn/otn/login/init')
# driver.maximize_window()
time.sleep(1)
driver.find_element_by_id('username').send_keys('使用者名稱')
time.sleep(0.5)
driver.find_element_by_id('password').send_keys('密碼')
# 將頁面進行截圖並儲存
driver.save_screenshot('12306登入頁面截圖.png')
# 確定驗證碼左上角和右下角的座標
code_img = driver.find_element_by_xpath('//*[@id="loginForm"]/div/ul[2]/li[4]/div/div/div[3]/img')
location = code_img.location # 確定驗證碼圖片左上角的座標
print('location:', location)
size = code_img.size # 確定驗證碼圖片的長和寬
print('size:', size)
rangle = (int(location['x']), int(location['y']), int(location['x']) + int(size['width']),
int(location['y']) + int(size['height']))
print('rangle:', rangle)
i = Image.open('12306頁面截圖.png')
# 對指定區域裁剪
code_pic = i.crop(rangle)
file_name = 'code_pic.png'
code_pic.save(file_name)
time.sleep(2)
print('驗證碼圖片儲存成功!!')
# 識別驗證座標
chaojiying = Chaojiying_Client('使用者賬號', '密碼', '開發者賬號') # 使用者中心>>軟體ID 生成一個替換 96001
im = open('code_pic.png', 'rb').read() # 本地圖片檔案路徑 來替換 a.jpg 有時WIN系統須要//
result = chaojiying.PostPic(im, 9004)['pic_str'] # 1902 驗證碼型別 官方網站>>價格體系 3.4+版 print 後要加()
all_list = [] # 儲存被點選的座標
if '|' in result:
list1 = result.split('|')
xy_list = []
count1 = len(list1)
for i in list1:
x = int(list1[i].split(',')[0])
xy_list.append(x)
y = int(list1[i].split(',')[1])
xy_list.append(y)
all_list.append(xy_list)
else:
xy_list = []
x = int(result.split(',')[0])
xy_list.append(x)
y = int(result.split(',')[1])
xy_list.append(y)
all_list.append(xy_list)
print(all_list)
# 迴圈遍歷點選圖片
for i in all_list:
x = i[0]
y = i[1]
action = ActionChains(driver).move_to_element_with_offset(code_img, x, y).click().perform()
time.sleep(1)
driver.find_element_by_id('loginSub').click()
如果對您有幫助,記得點贊加關注,謝謝!!!