Python火车票科普

引言

随着科技的发展和人们对出行需求的不断增加,火车票预订成为了现代生活中必不可少的一部分。Python作为一门功能强大且易于学习的编程语言,可以帮助我们自动化完成许多繁琐的任务,其中包括火车票预订。本篇文章将介绍如何使用Python来查询和预订火车票。

准备工作

在开始之前,我们需要安装一些Python库来帮助我们完成任务。其中包括requests库用于发送HTTP请求,beautifulsoup4库用于解析HTML文档。

你可以使用以下命令来安装这两个库:

$ pip install requests beautifulsoup4

查询火车票

要查询火车票,我们需要一个能够提供火车票信息的网站。以12306为例,我们可以通过发送HTTP请求并解析返回的HTML来获取所需的信息。

首先,我们需要导入所需的库:

import requests
from bs4 import BeautifulSoup

然后,我们可以使用requests.get()函数发送GET请求,并使用text属性获取返回的HTML内容:

response = requests.get('
html = response.text

接下来,我们可以使用beautifulsoup4库来解析HTML。首先,我们需要创建一个BeautifulSoup对象:

soup = BeautifulSoup(html, 'html.parser')

然后,我们可以使用该对象的方法来查找需要的元素。例如,如果我们想要查询从北京到上海的火车票信息,我们可以使用以下代码:

start_station = '北京'
end_station = '上海'

train_table = soup.find('table', class_='train-table')
rows = train_table.find_all('tr')

for row in rows:
    columns = row.find_all('td')
    if len(columns) > 3:
        if start_station in columns[1].text and end_station in columns[2].text:
            print(columns[0].text, columns[1].text, columns[2].text)

代码解析:

  • 首先,我们找到包含火车信息的表格元素,该元素具有train-table类。
  • 然后,我们找到所有的行元素,并在每一行中查找列元素。
  • 如果某一行的列元素数量大于3(即包含有效的火车信息),我们检查起始站和终点站是否与我们指定的一致。
  • 如果一致,我们打印出该火车的相关信息。

预订火车票

要预订火车票,我们需要模拟用户的操作来填写预订表单并提交。

首先,我们需要导入所需的库:

import requests
from bs4 import BeautifulSoup

然后,我们可以使用requests.get()函数发送GET请求,并使用text属性获取返回的HTML内容:

response = requests.get('
html = response.text

接下来,我们可以使用beautifulsoup4库来解析HTML。首先,我们需要创建一个BeautifulSoup对象:

soup = BeautifulSoup(html, 'html.parser')

然后,我们可以使用该对象的方法来查找需要的元素。例如,如果我们想要预订从北京到上海的火车票,我们可以使用以下代码:

start_station = '北京'
end_station = '上海'

train_table = soup.find('table', class_='train-table')
rows = train_table.find_all('tr')

for row in rows:
    columns = row.find_all('td')
    if len(columns) > 3:
        if start_station in columns[1].text and end_station in columns[2].text:
            link = columns[0].find('a')['href']
            break

booking_page = requests.get(link).text
booking_soup = BeautifulSoup(booking_page, 'html.parser')

booking_form = booking_soup.find('form', class_='booking-form')
input_fields = booking_form.find_all('input')

data = {}
for field in input_fields:
    if 'name' in field.attrs:
        data[field['name']] = field.get('value', '')

data['username'] = 'your_username'
data['password'] = 'your_password'

response = requests.post(' data=data)

代码解析:

  • 首先,我们找到包含火车信息的表格