可使用 Python 爬取火车票网站,步骤如下:安装 requests 和 BeautifulSoup 库。获取火车票网站的 URL。发送 HTTP GET 请求以获取网页。使用 BeautifulSoup 解析 HTML 响应。通过 CSS 选择器或 XPath 提取所需数据,例如出发站、票价等。存储或显示提取的数据。

使用 Python 爬取火车票网站
如何使用 Python 爬取火车票网站?
要使用 Python 爬取火车票网站,可以按照以下步骤进行:
pip 安装 requests 和 BeautifulSoup 库。requests 库发送 HTTP GET 请求以获取网页。BeautifulSoup 库解析 HTML 响应。具体示例
立即学习“Python免费学习笔记(深入)”;
以下是用 Python 爬取火车票网站的代码示例:
<code class="python">import requests
from bs4 import BeautifulSoup
# 获取火车票网站的 URL
url = "https://www.example.com/train-tickets"
# 发送 HTTP GET 请求
response = requests.get(url)
# 解析 HTML 响应
soup = BeautifulSoup(response.text, "html.parser")
# 提取火车票信息
train_tickets = []
for ticket in soup.find_all("div", class_="train-ticket"):
departure_station = ticket.find("span", class_="departure-station").text
arrival_station = ticket.find("span", class_="arrival-station").text
departure_time = ticket.find("span", class_="departure-time").text
arrival_time = ticket.find("span", class_="arrival-time").text
price = ticket.find("span", class_="price").text
train_tickets.append({
"departure_station": departure_station,
"arrival_station": arrival_station,
"departure_time": departure_time,
"arrival_time": arrival_time,
"price": price
})
# 显示火车票信息
for ticket in train_tickets:
print(f"{ticket['departure_station']} -> {ticket['arrival_station']}: {ticket['departure_time']} - {ticket['arrival_time']} (${ticket['price']})")</code>以上就是用python爬虫火车票网站的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号