import re, json, time
from selenium import webdriver
def get_ticket():
from_city = input("出发站:")
to_city = input("到达站:")
date = input("出发日期(格式:2019-12-30):")
file_name = input("存储文件:")
driver = webdriver.Chrome()
# 起始url
url = 'https://www.12306.cn/index/'
# 发送请求
driver.get(url)
# 等待2s
time.sleep(2)
# 清除原有的值
driver.find_element_by_id('fromStationText').clear()
# 点击,使输入框获取焦点
driver.find_element_by_id('fromStationText').click()
# 输入值
driver.find_element_by_id('fromStationText').send_keys(from_city)
# 获取局部刷新的数据,然后循环比对文字
from_text = driver.find_elements_by_class_name('ralign')
# 下拉选项中选择对应车站并点击
for i in from_text:
if i.text == from_city: i.click(); break
# 输入到达地(原理同上)
driver.find_element_by_id('toStationText').clear()
driver.find_element_by_id('toStationText').click()
driver.find_element_by_id('toStationText').send_keys(to_city)
to_text = driver.find_elements_by_class_name('ralign')
for i in to_text:
if i.text == to_city: i.click(); break
# 选择出发时间
driver.execute_script("document.getElementById('train_date').value='{}'".format(date))
# 点击查询
driver.find_element_by_id("search_one").click()
# 切换到数据页
windows = driver.window_handles
function(){ //XM返佣 http://www.kaifx.cn/broker/xm.html
driver.switch_to.window(windows[-1])
time.sleep(2)
# 提取数据页数据
all_tr = driver.find_elements_by_xpath("//*[@id='queryLeftTable']/tr")
li = list()
# 保存数据
for tr in all_tr[::2]:
dic = dict()
data = re.sub(r'\n', " ", tr.text).split(' ')
dic["日期"] = date
dic["车次"] = data[0]
dic["出发站"] = data[1]
dic["到达站"] = data[2]
dic["出发时间"] = data[3]
dic["到达时间"] = data[4]
dic["历时"] = data[5]
dic["到达日期"] = data[6]
dic["商务座"] = data[7]
dic["一等座"] = data[8]
dic["二等座"] = data[9]
dic["高级软卧"] = data[10]
dic["一等软卧"] = data[11]
dic["动卧"] = data[12]
dic["二等硬卧"] = data[13]
dic["软座"] = data[14]
dic["硬座"] = data[15]
dic["无座"] = data[16]
dic["其他"] = data[17]
dic["备注"] = data[18]
print(dic)
li.append(dic)
json.dump(li, open("ticket_" + file_name + ".json", "w", encoding="utf-8"), ensure_ascii=False) if li else print(
"很抱歉,当前未找到从{} 到{} 的列车。".format(from_city, to_city))
time.sleep(2)
# 关闭浏览器,退出浏览器
driver.close()
driver.quit()
get_ticket()
Python查询火车票
最新推荐文章于 2021-02-10 16:32:49 发布