在开始编写抢票软件之前,需要安装一些必要的库,这里我们使用Python的第三方库requests
和beautifulsoup4
来实现网络请求和网页解析。
pip install requests beautifulsoup4
我们需要登录12306官网,获取登录后的cookies信息,这样在后续的抢票过程中,我们就可以使用这个cookies信息来保持登录状态。
import requests
from bs4 import BeautifulSoup
def login(username, password):
login_url = "https://kyfw.12306.cn/otn/login/init"
s = requests.Session()
s.get(login_url)
# 在这里填写你的用户名和密码
data = {
"username": username,
"password": password,
}
response = s.post(login_url, data=data)
soup = BeautifulSoup(response.text, "html.parser")
cookies = s.cookies.get_dict()
return cookies
username = "your_username"
password = "your_password"
cookies = login(username, password)
登录成功后,我们需要查询指定日期和出发地、目的地的车次信息,这里我们使用requests
库发送网络请求,使用beautifulsoup4
库解析返回的HTML页面。
def search_trains(date, from_station, to_station, cookies):
search_url = "https://kyfw.12306.cn/otn/leftTicket/query"
params = {
"leftTicketDTO.train_date": date,
"leftTicketDTO.from_station": from_station,
"leftTicketDTO.to_station": to_station,
"purpose_codes": "ADULT",
}
response = requests.get(search_url, params=params, cookies=cookies)
trains = response.json()["data"]["result"]
return trains
date = "20221201"
from_station = "SHH" # 上海虹桥站
to_station = "BJP" # 北京西站
trains = search_trains(date, from_station, to_station, cookies)
根据查询到的车次信息,我们可以开始抢票了,这里我们使用requests
库发送网络请求,实现自动提交订单和支付功能。
def book_ticket(train_no, seat_type, cookies):
book_url = "https://kyfw.12306.cn/otn/confirmPassenger/initDc"
data = {
"train_no": train_no,
"seat_type": seat_type,
}
response = requests.post(book_url, data=data, cookies=cookies)
if "预订成功" in response.text:
print("抢票成功!")
else:
print("抢票失败!")
train_no = "G101" # 高铁G101次
seat_type = "二等座" # 二等座
book_ticket(train_no, seat_type, cookies)
注意:以上代码仅供参考,实际使用时可能需要根据12306官网的实际情况进行调整,抢票行为可能违反12306官网的规定,请谨慎使用。