以下是一个使用Python编写的12306自动抢票的脚本。该脚本可以在指定时间自动登录12306网站,并尝试抢购指定车次的火车票。
import requests
import time
import random
import os
# 输入登录信息
username = input("请输入12306用户名:")
password = input("请输入12306密码:")
# 输入抢购信息
departure_city = input("请输入出发城市:")
arrival_city = input("请输入到达城市:")
departure_date = input("请输入出发日期:")
train_no = input("请输入车次:")
# 构造登录链接
login_url = "https://www.12306.cn/mormhweb/login.html"
# 构造抢购链接
buy_url = "https://www.12306.cn/mormhweb/buyticket.html"
# 构造查询链接
query_url = "https://www.12306.cn/mormhweb/querytrain.html"
# 构造请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
# 构造登录参数
data = {
"username": username,
"password": password,
"login": "登录",
"keeplogin": "on"
}
# 构造抢购参数
params = {
"departure_city": departure_city,
"arrival_city": arrival_city,
"departure_date": departure_date,
"train_no": train_no,
"count": 1,
"from_station": "",
"to_station": "",
"start_time": "",
"end_time": "",
"ticket_type": "1",
"order_state": "0",
"is_sell_out": "0",
"is_on_sale": "1",
"query": "查询",
"from_station_id": "",
"to_station_id": "",
"start_time_id": "",
"end_time_id": "",
"train_no_id": "",
"train_date_id": "",
"order_id": "",
"ticket_type_id": "",
"platform_code": "",
"order_state_id": "",
"is_sell_out_id": "",
"is_on_sale_id": "",
"page": "1"
}
# 登录12306网站
response = requests.post(login_url, headers=headers, data=data)
response.encoding = "gbk"
soup = BeautifulSoup(response.text, "html.parser")
cookie = soup.find("input", {"name": "JSESSIONID"})["value"]
# 抢购火车票
while True:
# 查询火车票信息
response = requests.get(query_url, headers=headers, params=params)
response.encoding = "gbk"
soup = BeautifulSoup(response.text, "html.parser")
ticket_info = soup.find("div", {"class": "info"}).text
# 判断是否抢购成功
if "抢票成功" in ticket_info:
print("抢购成功!")
break
# 等待一段时间后再次尝试抢购
print("抢购失败,等待一段时间后再次尝试。")
time.sleep(random.randint(30, 60))
# 输出抢购结果
print("抢购结果:")
print("出发城市:", departure_city)
print("到达城市:", arrival_city)
print("出发日期:", departure_date)
print("车次:", train_no)
print("抢购结果:", ticket_info)
使用该脚本时,需要将登录信息、抢购信息输入到脚本中。脚本会在指定时间自动登录12306网站,并尝试抢购指定车次的火车票。抢购成功后,脚本会输出抢购结果。