使用 Python 爬虫查询火车票需要以下步骤:安装 requests 库用于发送 HTTP 请求。安装 beautifulsoup4 库用于解析 HTML。使用 requests.get() 函数获取火车票查询网站的 HTML 源码。使用 BeautifulSoup 库解析 HTML 源码。使用 find() 和 find_all() 方法从 HTML 中提取火车票信息。遍历

Python 爬虫查询火车票
如何使用 Python 爬虫查询火车票?
使用 Python 爬虫查询火车票需要以下步骤:
安装必要的库
立即学习“Python免费学习笔记(深入)”;
pip install requests 安装 requests 库用于发送 HTTP 请求。pip install beautifulsoup4 安装 beautifulsoup4 库用于解析 HTML。获取 HTML 源码
requests.get() 函数从火车票查询网站获取 HTML 源码。html = requests.get("https://www.12306.cn/index/").text
解析 HTML 源码
BeautifulSoup 库解析 HTML 源码。soup = BeautifulSoup(html, "html.parser")
提取火车票信息
find() 和 find_all() 方法从 HTML 中提取火车票信息。trains = soup.find_all("tr", {"class": "train-item"})
解析火车票信息
例如:
<code class="python">for train in trains:
departure_station = train.find("td", {"class": "station"}).text
arrival_station = train.find("td", {"class": "station", "style": "text-align: right;"}).text
departure_time = train.find("td", {"class": "time"}).text
arrival_time = train.find("td", {"class": "time", "style": "text-align: right;"}).text
tickets_left = train.find("td", {"class": "ticket"}).text</code>示例代码
<code class="python">import requests
from bs4 import BeautifulSoup
html = requests.get("https://www.12306.cn/index/").text
soup = BeautifulSoup(html, "html.parser")
trains = soup.find_all("tr", {"class": "train-item"})
for train in trains:
departure_station = train.find("td", {"class": "station"}).text
arrival_station = train.find("td", {"class": "station", "style": "text-align: right;"}).text
departure_time = train.find("td", {"class": "time"}).text
arrival_time = train.find("td", {"class": "time", "style": "text-align: right;"}).text
tickets_left = train.find("td", {"class": "ticket"}).text
print(f"{departure_station} --> {arrival_station}, 出发时间:{departure_time}, 到达时间:{arrival_time}, 余票:{tickets_left}")</code>以上就是python爬虫查询火车票的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号