python+selenium中国鉄道12306自動登録を実現
関連する知識点: selenium自動化テストツールの使用(基本的なクリック、テキスト入力、動作チェーン実行) 12306ピクチャ検証コードの解読(ポイント選択クラス検証コード) 実装された効果:ケースコード:
from selenium import webdriver
from selenium.webdriver import ActionChains
import base64
import requests
import re
import time
def login():
username =
password =
driver.get('https://kyfw.12306.cn/otn/resources/login.html')
driver.maximize_window()
#driver.set_window_size(1600,900)
#
driver.implicitly_wait(10) # 10 ,10 , ;
# ,
"""
implicitly_wait():
, WebDriver DOM , ,
, , DOM, 0
, WebDriver , ,
, 。
"""
driver.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a').click()
driver.find_element_by_xpath('//*[@id="J-userName"]').send_keys(username)
driver.find_element_by_xpath('//*[@id="J-password"]').send_keys(password)
# base64
img_url = driver.find_element_by_xpath('//*[@id="J-loginImg"]').get_attribute('src')
"""
base64
:1. ( css , )
2. http
3. ,
"""
print(' url',img_url)
get_image(img_url)
ysm_result = yzm_resolve()
#
click_yzm_result(ysm_result)
#
driver.find_element_by_xpath('//*[@id="J-login"]').click()
#
driver.implicitly_wait(10)
def get_image(img_url):
"""base64 , """
#
base64_url = img_url.split(',')[1]
# base64
img_data = base64.b64decode(base64_url)
with open('yzm.jpg',mode='wb') as f:
f.write(img_data)
def yzm_resolve():
""" """
# http://littlebigluo.qicp.net:47720/
img_data = open('yzm.jpg',mode="rb")
file = {'pic_xxfile':img_data}
url = 'http://littlebigluo.qicp.net:47720/'
resp = requests.post(url=url,files=file)
result = []
for i in re.findall('(.*?)',resp.text)[0].split(' '):
result.append(int(i))
print(" :",result)
img_data.close()
return result
def click_yzm_result(result):
""" ( )"""
# ActionChains
img_element = driver.find_element_by_xpath('//*[@id="J-loginImg"]')
print(" ...")
action = ActionChains(driver)
for i in result:
# 8 , , ( 0,0 )
# MAP = [[-105,-20], [-35,-20], [40,-20], [110,-20], [-105,50], [-35,50], [40,50], [110,50]]
MAP = [[-135,-45], [-45,-45], [45,-45], [135,-45],
[-135,45], [-45,45], [45,45], [135,45]]
# 1.2.3.4.5.6.7.8
action.move_to_element(img_element).move_by_offset(MAP[i-1][0],MAP[i-1][1]).click()
# ,
time.sleep(1) # 1
#
print(" ")
action.perform()
time.sleep(1)
if __name__ == '__main__':
driver = webdriver.Chrome()
login()