一. 代碼使用Python+Splinter開發,Splinter是一個使用Python開發的開源Web應用測試工具,它可以幫你實現自動瀏覽站點和與其進行交互。
二. 安裝好Python 3或2都可以,然后安裝Splinter `pip install Splinter
三. Splinter注意事項
1. Splinter的Browser類默認優先使用firefox,所以用chrome的話,需要指定driver_name="chrome",只要養成一個習慣,不管用什么瀏覽器都指定,問題會出得少
2. 當然,選擇chrome的話,需要查看自己瀏覽器的版本,需要和chromedriver版本對應(不是版本號一致),參考和下載地址
四. Splinter.broser部分方法介紹
1. findbyid("控件id").first:根據id找到組件
2. visis(url):訪問指定網址
3. fill("填充的內容"):用指定內容填充組件
4. click():點擊事件
5. reload():重新加載當前文檔
五. 主要思路:
1. 自動填充用戶名,密碼,點擊圖片驗證碼(手動),自動點擊購票查詢,預訂,自動選擇指定乘客進入提交訂單頁面
2. 除登錄時的圖片驗證碼,全程自動
六. error(下面是我已經嘗試成功的):
1. OSError: [WinError 193] %1 不是有效的 Win32 應用程序。
2. 解決方案:chromedriver版本和電腦瀏覽器版本映射沒對應
3. ImportError: cannot import name 'Browser'。
4. 解決方案:是否安裝了Splinter `pip install Splinter`,將代碼文件和chromedriver放到一個新文件夾下,防止其他文件的影響
5. 請在運行文件前,將代碼內的乘客,用戶名,密碼正確填寫好,檢查cookies是否正確
七. cookies 查看
1. 進入chrome瀏覽器,按F12,選中NetWork選項,如下圖
2. 起始地址:`_jc_save_fromStation` 購票時間:`_jc_save_fromDate` 目的地:`_jc_save_toStation`
八. 運行方法
1. python trainticket.py 福建 廈門 2020-11-11
2. OK
九. 具體代碼如下
1 # -*- coding:utf-8 -*- 2 """ 3 @author Jianxiong Rao 4 """ 5 from splinter.browser import Browser 6 from time import sleep 7 import traceback 8 import time,sys 9 import os 10 11 class HuoChe(object): 12 """docstring for Train""" 13 driver_name='' 14 executable_path='' 15 #用戶名 密碼 16 username = u"12306帳戶名" 17 passwd = u"12306密碼" 18 #cookies值自己找 19 # 天津%u5929%u6D25%2CTJP 南昌%u5357%u660C%2CNCG 桂林%u6842%u6797%2CGLZ 20 starts = u"%u5929%u6D25%2CTJP" 21 ends = u"%u5357%u660C%2CNCG" 22 #時間格式2018-02-05 23 dtime = u"2018-02-05" 24 #車次,選擇第幾趟,0則從上之下依次點擊 25 order = 0 26 ###乘客姓名 27 users=[u'乘客名'] 28 ##席位 29 xb=u"二等座" 30 pz=u"成人票" 31 """網址""" 32 #12306查詢URL 33 ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init" 34 #12306登錄URL 35 login_url = "https://kyfw.12306.cn/otn/login/init" 36 #我的12306URL 37 initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306" 38 #購票URL 39 buy="https://kyfw.12306.cn/otn/confirmPassenger/initDc" 40 login_url='https://kyfw.12306.cn/otn/login/init' 41 42 def __init__(self): 43 self.driver_name = 'chrome' 44 self.executable_path = os.getcwd()+'/chromedriver' 45 print("Welcome To Use The Tool") 46 47 def login(self): 48 self.driver.visit(self.login_url) 49 #填充密碼 50 self.driver.fill("loginUserDTO.user_name",self.username) 51 #sleep(1) 52 self.driver.fill("userDTO.password",self.passwd) 53 print("等待驗證碼,自行輸入....") 54 while True: 55 if self.driver.url != self.initmy_url: 56 sleep(1) 57 else : 58 break 59 def start(self): 60 self.driver = Browser(driver_name=self.driver_name,executable_path = self.executable_path) 61 self.driver.driver.set_window_size(1400,1000) 62 self.login() 63 #sleep(1) 64 self.driver.visit(self.ticket_url) 65 try: 66 print("購票頁面開始....") 67 #sleep(1) 68 #加載查詢信息 69 self.driver.cookies.add({"_jc_save_fromStation":self.starts}) 70 self.driver.cookies.add({"_jc_save_toStation":self.ends}) 71 self.driver.cookies.add({"_jc_save_fromDate":self.dtime}) 72 73 self.driver.reload() 74 75 count = 0 76 if self.order != 0: 77 while self.driver.url == self.ticket_url: 78 self.driver.find_bytext(u"查詢").click() 79 count += 1 80 print("循環點擊查詢.... 第 %s 次"%count) 81 #sleep(1) 82 try: 83 self.driver.find_by_text(u'預訂')[self.order - 1].click() 84 except Exception as e: 85 print(e) 86 print("還沒開始預訂") 87 continue 88 else : 89 while self.driver.url == self.ticket_url: 90 self.driver.find_by_text(u"查詢").click() 91 count += 1 92 print("循環點擊查詢.... 第 %s 次"%count) 93 #sleep(0.8) 94 try: 95 for i in self.driver.find_by_text(u"預訂"): 96 i.click() 97 sleep(1) 98 except Exception as e: 99 print(e) 100 print("還沒開始預訂 %s "%count) 101 continue 102 print("開始預訂....") 103 #sleep(1) 104 #self.driver.reload() 105 sleep(1) 106 print("開始選擇用戶....") 107 for user in self.users: 108 self.driver.find_by_text(user).last.click() 109 print("提交訂單....") 110 sleep(1) 111 # self.driver.find_by_text(self.pz).click() 112 # self.driver.find_by_id('').select(self.pz) 113 # sleep(1) 114 # self.driver.find_by_text(self.xb).click() 115 # sleep(1) 116 self.driver.find_by_id('submitOrder_id').click() 117 print("開始選座...") 118 # self.driver.find_by_id('1D').last.click() 119 # self.driver.find_by_id('1F').last.click() 120 sleep(1.5) 121 print("確認選座....") 122 self.driver.find_by_text('qr_submit_id').click() 123 124 except Exception as e: 125 print(e) 126 127 cities={ 128 '福建':'%u5929%u6D25%2CTJP', 129 '廈門':'%u5357%u660C%2CNCG', 130 131 } 132 133 if __name__=="__main__": 134 train = HuoChe() 135 train.starts = cities[sys.argv[1]] 136 train.ends = cities[sys.argv[2]] 137 train.dtime = sys.argv[3] 138 train.start()
# -*- coding:utf-8 -*-
"""
@author Jianxiong Rao
"""
from
splinter.browser
import
Browser
from
time
import
sleep
import
traceback
import
time,sys
import
os
class
HuoChe(
object
):
"""docstring for Train"""
driver_name
=
''
executable_path
=
''
#用戶名 密碼
username
=
u
"12306帳戶名"
passwd
=
u
"12306密碼"
#cookies值自己找
# 天津%u5929%u6D25%2CTJP 南昌%u5357%u660C%2CNCG 桂林%u6842%u6797%2CGLZ
starts
=
u
"%u5929%u6D25%2CTJP"
ends
=
u
"%u5357%u660C%2CNCG"
#時間格式2018-02-05
dtime
=
u
"2018-02-05"
#車次,選擇第幾趟,0則從上之下依次點擊
order
=
0
###乘客姓名
users
=
[u
'乘客名'
]
##席位
xb
=
u
"二等座"
pz
=
u
"成人票"
"""網址"""
#12306查詢URL
#12306登錄URL
#我的12306URL
#購票URL
def
__init__(
self
):
self
.driver_name
=
'chrome'
self
.executable_path
=
os.getcwd()
+
'/chromedriver'
print
(
"Welcome To Use The Tool"
)
def
login(
self
):
self
.driver.visit(
self
.login_url)
#填充密碼
self
.driver.fill(
"loginUserDTO.user_name"
,
self
.username)
#sleep(1)
self
.driver.fill(
"userDTO.password"
,
self
.passwd)
print
(
"等待驗證碼,自行輸入...."
)
while
True
:
if
self
.driver.url !
=
self
.initmy_url:
sleep(
1
)
else
:
break
def
start(
self
):
self
.driver
=
Browser(driver_name
=
self
.driver_name,executable_path
=
self
.executable_path)
self
.driver.driver.set_window_size(
1400
,
1000
)
self
.login()
#sleep(1)
self
.driver.visit(
self
.ticket_url)
try
:
print
(
"購票頁面開始...."
)
#sleep(1)
#加載查詢信息
self
.driver.cookies.add({
"_jc_save_fromStation"
:
self
.starts})
self
.driver.cookies.add({
"_jc_save_toStation"
:
self
.ends})
self
.driver.cookies.add({
"_jc_save_fromDate"
:
self
.dtime})
self
.driver.
reload
()
count
=
0
if
self
.order !
=
0
:
while
self
.driver.url
=
=
self
.ticket_url:
self
.driver.find_bytext(u
"查詢"
).click()
count
+
=
1
print
(
"循環點擊查詢.... 第 %s 次"
%
count)
#sleep(1)
try
:
self
.driver.find_by_text(u
'預訂'
)[
self
.order
-
1
].click()
except
Exception as e:
print
(e)
print
(
"還沒開始預訂"
)
continue
else
:
while
self
.driver.url
=
=
self
.ticket_url:
self
.driver.find_by_text(u
"查詢"
).click()
count
+
=
1
print
(
"循環點擊查詢.... 第 %s 次"
%
count)
#sleep(0.8)
try
:
for
i
in
self
.driver.find_by_text(u
"預訂"
):
i.click()
sleep(
1
)
except
Exception as e:
print
(e)
print
(
"還沒開始預訂 %s "
%
count)
continue
print
(
"開始預訂...."
)
#sleep(1)
#self.driver.reload()
sleep(
1
)
print
(
"開始選擇用戶...."
)
for
user
in
self
.users:
self
.driver.find_by_text(user).last.click()
print
(
"提交訂單...."
)
sleep(
1
)
# self.driver.find_by_text(self.pz).click()
# self.driver.find_by_id('').select(self.pz)
# sleep(1)
# self.driver.find_by_text(self.xb).click()
# sleep(1)
self
.driver.find_by_id(
'submitOrder_id'
).click()
print
(
"開始選座..."
)
# self.driver.find_by_id('1D').last.click()
# self.driver.find_by_id('1F').last.click()
sleep(
1.5
)
print
(
"確認選座...."
)
self
.driver.find_by_text(
'qr_submit_id'
).click()
except
Exception as e:
print
(e)
cities
=
{
'天津'
:
'%u5929%u6D25%2CTJP'
,
'南昌'
:
'%u5357%u660C%2CNCG'
,
'桂林'
:
'%u6842%u6797%2CGLZ'
}
if
__name__
=
=
"__main__"
:
train
=
HuoChe()
train.starts
=
cities[sys.argv[
1
]]
train.ends
=
cities[sys.argv[
2
]]
train.dtime
=
sys.argv[
3
]
train.start()