去年过年照着网上的做的,用splinter或者selenium都可以实现。这两个库是实现web浏览器自动操作的库。就是模拟人的点击等等一系列操作。
不过先对应你的谷歌浏览器版本下好对应的chromedriver,然后添加好环境变量
# -*- coding: utf-8 -*-
from splinter.browser import Browser
from time import sleep
import time
import pygame
from selenium.webdriver.support.select import Select
from selenium import webdriver
from selenium.webdriver.support.select import Select
class ticket(object):
# 用户名,密码
username = u"用户名"
passwd = u"密码"
# 车次,选择第几趟,0则从上之下依次点击
order = 0
ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init"
login_url = "https://kyfw.12306.cn/otn/login/init"
initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306"
buy = "https://kyfw.12306.cn/otn/confirmPassenger/initDc"
def login(self):
self.driver.get(self.login_url)
# 填充密码
self.driver.find_element_by_name("loginUserDTO.user_name").send_keys(self.username)
self.driver.find_element_by_name("userDTO.password").send_keys(self.passwd)
print(u"等待验证码,自行输入...")
print("开始登录")
sleep(5)
while True:
if self.driver.current_url!= self.initmy_url:
sleep(1)
else:
break
print("结束登录")
def start(self):
self.driver = webdriver.Chrome()
self.login()
sleep(3)
self.driver.get(self.ticket_url)
try:
print(u"购票页面开始...")
self.driver.find_element_by_id("fromStationText").send_keys("长沙")
self.driver.find_element_by_id("toStationText").send_keys("石门北")
self.driver.find_element_by_id("train_date").send_keys("2018-03-28")
# K-快速 Z-直达 D-动车 GC-高铁/城际 T-特快
count = 0
if self.order != 0:
while self.driver.url == self.ticket_url:
self.driver.find_by_text(u"查询").click()
count += 1
print(u"点击查询... 第 %s 次" % count)
sleep(0.8)
try:
self.driver.find_by_text(u"预订")[self.order - 1].click()
except Exception as e:
print(e)
print(u"预订。。。")
continue
else:
while self.driver.url == self.ticket_url:
self.driver.find_by_text(u"查询").click()
count += 1
print(u"点击查询... 第 %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(u"预订 。。。")
continue
print(u"开始预订...")
sleep(3)
sleep(1)
print(u"开始选择用户...")
self.driver.find_by_text(u"熊桐").last.click()
print(u"提交订单...")
sleep(1)
time.sleep(60)
self.driver.find_by_id('submitOrder_id').click()
sleep(1.5)
self.driver.find_by_id('qr_submit_id').click()
pygame.mixer.init()
print("订单完成,播放音乐提醒")
track = pygame.mixer.music.load(file)
pygame.mixer.music.play()
time.sleep(60)
pygame.mixer.music.stop()
except Exception as e:
print(e)
cities = {
'北京': '%u5317%u4EAC%2CBJP',
'广州': '%u5E7F%u5DDE%2CGZQ',
'杭州': '%u676D%u5DDE%2CHZH',
'深圳': '%u6DF1%u5733%2CSZQ',
'武汉': '%u6B66%u6C49%2CWHN',
'上海': '%u4E0A%u6D77%2CSHH',
'长沙': '%u957F%u6C99%2CCSQ',
'石门北': '%u77F3%u95E8%u53BF%u5317%2CVFQ'}
if __name__ == '__main__':
file = r'.\PycharmProjects\untitled3\她说.mp3'
ticket = ticket()
ticket.starts = cities["长沙"]
ticket.ends = cities["石门北"]
ticket.dtime = "2018-03-28"
ticket.start()