马上就要过年了,听说还有人买不到票?

不要慌,今天咱们来用Python做一个自动查票抢票的脚本,24小时抢票,谁抢的过你!

 

准备工作

环境

Python 3.8

Pycharm

插件

谷歌浏览器驱动

模块

需要安装的第三方模块,直接pip安装即可。

requests # 数据请求模块

prettytable # 打印好看一些

selenium # 模拟人的行为去操作浏览器

 

文件素材

city.json文件

# 下图素材、视频、代码、插件安装教程我都准备好了,直接在这个q君羊708525271自取就好了

 

一点小TIPS

12306 每天只能退票三次

查票购票

建议谷歌或者火狐…

爬虫思路

分析数据来源

车票信息:来源哪个数据包 <车票信息请求那个网站url地址可以得到>

开发者工具:F12

代码实现步骤

1、发送请求, 对于刚刚分析得到url地址发送请求。2、获取数据, 获取服务器返回响应数据, response3、解析数据, 提取我们想要车次信息。

# 导入数据请求模块

import requests

# 导入格式化打印

import prettytable as pt

# 导入json

import json

# 导入自动化测试模块

from selenium import webdriver

# 导入账号密码

from password import account, Password

# 导入时间模块

import time

# 导入键盘控制

from selenium.webdriver.common.keys import Keys

 

打开浏览器。

driver = webdriver.Chrome()

 

绕过检测机制

driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",

{"source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"""})

 

输入网址

driver.get('https://kyfw.12306.cn/otn/resources/login.html')

 

输入账号密码

先找到账号密码输入框, 再进行输入操作。

try:

# 输入账号

driver.find_element_by_css_selector('#J-userName').send_keys(account)

# 输入密码

driver.find_element_by_css_selector('#J-password').send_keys(Password)

# 点击登陆

driver.find_element_by_css_selector('#J-login').click()

# 延时

driver.implicitly_wait(10)

time.sleep(1)

 

点击弹窗

driver.implicitly_wait(10) # 延时等待 为了让网页元素加载

time.sleep(1)

driver.find_element_by_css_selector('.btn').click()

 

点击车票预定

driver.find_element_by_css_selector('#link_for_ticket').click()

 

选择城市以及时间, 点击查询

driver.find_element_by_css_selector('#fromStationText').click() # 点击输入框

driver.find_element_by_css_selector('#fromStationText').clear() # 清空输入框

driver.find_element_by_css_selector('#fromStationText').send_keys('长沙') # 输入内容

driver.find_element_by_css_selector('#fromStationText').send_keys(Keys.ENTER) # 回车按钮

# 输入到达的城市

driver.find_element_by_css_selector('#toStationText').click() # 点击输入框

driver.find_element_by_css_selector('#toStationText').clear() # 清空输入框

driver.find_element_by_css_selector('#toStationText').send_keys('上海') # 输入内容

driver.find_element_by_css_selector('#toStationText').send_keys(Keys.ENTER) # 回车按钮

# 输入时间

driver.find_element_by_css_selector('#train_date').click() # 点击输入框

driver.find_element_by_css_selector('#train_date').clear() # 清空输入框

driver.find_element_by_css_selector('#train_date').send_keys('2022-11-09') # 输入内容

# 点击查询按钮

driver.find_element_by_css_selector('#query_ticket').click()

# 点击预定

driver.find_element_by_css_selector('#queryLeftTable tr:nth-child(1) .btn72').click()

# 选择乘车人

driver.find_element_by_css_selector('#normalPassenger_1').click()

# 点击提交提单

driver.find_element_by_css_selector('#submitOrder_id').click()

# 选择座位

# driver.find_element_by_css_selector('#erdeng1 > ul:nth-child(4) > li:nth-child(2)').click()

# 点击提交

time.sleep(3)

driver.find_element_by_css_selector('#qr_submit_id').click()

driver.find_element_by_css_selector('#qr_submit_id').click()

 

发送请求, 模拟浏览器对url地址发送请求

# 读取文件 城市字母文件

f = open('city.json', encoding='utf-8')

# f.read() 返回字符串数据类型 把字符串转成json字典数据 --> 根据键值对取值

json_data = json.loads(f.read())

# 输入内容

from_city = input('请输入你要出发城市: ')

to_city = input('请输入你要到达城市: ')

date = '2022-11-09'

# 确定请求链接

url = f'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={date}&leftTicketDTO.from_station={json_data[from_city]}&leftTicketDTO.to_station={json_data[to_city]}&purpose_codes=ADULT'

# 模拟伪装 ---> headers 请求头

headers = {

# Cookie 用户信息, 表示常用于检测是否有登陆账号

'Cookie': '_uab_collina=165650330916153394558455; JSESSIONID=34AFEC7D7370756179A2976A79434D6A; _jc_save_wfdc_flag=dc; _jc_save_fromStation=%u957F%u6C99%2CCSQ; BIGipServerotn=1911030026.24610.0000; BIGipServerpassport=770179338.50215.0000; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; RAIL_EXPIRATION=1668129535127; RAIL_DEVICEID=TbHG0I9N4zNOVXocTOo6JdSREGznbbsYb5f_xQPshKLa1Y8Qx7LbGMu_h4Zwb6MyBOk_1zvlhZn85dlBcC4F1SEL1hwpTWuAkNkA7dSIqQ-dgdZAcoL1jMCS4bWfKSgKEstpGs8BAzfO-ItsTfKkP6YQL9Y24vGA; fo=uyys4j4q4rs7diywCDbOKBwdzYaDJcHjbyEG0hwDDZbF9Swz2dB79o6CCDC_EOHwJ7XidDtuZKQKjz6vYdfE3PDpSX9YvVulaMDDQmKGRPhrjzRZHlNGKC2S6egp70_4PJGqyv770aRXnJgffGRwkABzbJZDDiUtaTyHzatcoZpt_YO-T-dfbdjNQrQ; route=9036359bb8a8a461c164a04f8f50b252; _jc_save_toStation=%u4E0A%u6D77%2CSHH; _jc_save_fromDate=2022-11-09; _jc_save_toDate=2022-11-07',

# User-Agent 用户代理 表示浏览器基本身份信息

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36'

}

# 发送请求

response = requests.get(url=url, headers=headers)

# 表示请求成功了

print(response)

 

获取数据,获取服务器返回响应数据。

为什么获取response.json() 数据的时候报错?simplejson.errors.JSONDecodeError: Expecting value: line 1 column 4 (char 3)一定获取的数据, 不是完整json数据格式

解决方法:

获取response.text 看数据返回情况发现自己获取的数据, 和开发者工具里面所看到不一样 <因为你被反爬了 [要么得不到数据, 要么得到数据不是想要的]>

因为没有伪装, 加headers 伪装一下

解析数据, 提取我们想要车次信息

response.json() # 获取响应json字典数据 完整的花括号

response.text # 获取响应文本数据 字符串数据

 

根据基础语法知识点: 字典取值 --> 键值对取值, 根据冒号左边的内容[键], 提取冒号有右边的内容[值]

# 实例化一个对象

tb = pt.PrettyTable()

# 输出添加字段名

tb.field_names = [

'序号',

'车次',

'出发时间',

'到达时间',

'耗时',

'特等座',

'一等',

'二等',

'软卧',

'硬卧',

'硬座',

'无座',

]

# 添加序号 每次循环+1

page = 0

# for循环遍历, 把列表里面元素 一个一个提出来

for i in response.json()['data']['result']:

# 先用 split 分割, 再用列表取值: 根据索引位置

index = i.split('|')

num = index[3] # 车次

start_time = index[8] # 出发时间

end_time = index[9] # 到达时间

use_time = index[10] # 耗时

topGrade = index[32] # 特等座

first_class = index[31] # 一等

second_class = index[30] # 二等

hard_sleeper = index[28] # 硬卧

hard_seat = index[29] # 硬座

no_seat = index[26] # 无座

soft_sleeper = index[23] # 软卧

dit = {

'序号': page,

'车次': num,

'出发时间': start_time,

'到达时间': end_time,

'耗时': use_time,

'特等座': topGrade,

'一等': first_class,

'二等': second_class,

'软卧': soft_sleeper,

'硬卧': hard_sleeper,

'硬座': hard_seat,

'无座': no_seat,

}

# print(dit)

# 添加每行输出内容

tb.add_row([page, num, start_time, end_time,

use_time,

topGrade,

first_class,

second_class,

soft_sleeper,

hard_sleeper,

hard_seat,

no_seat,

])

page += 1 # 每次循环+1

 

今天的分享就到这里结束了,觉得有用的话,记得点餐收藏呀!

查看原文