python 爬取火车票价格
时间: 2023-12-25 12:30:12 浏览: 31
以下是使用Python爬取火车票价格的示例代码:
```python
import requests
import json
# 发送请求获取火车票信息
url = "https://www.example.com/train_tickets"
response = requests.get(url)
# 解析返回的JSON数据
data = json.loads(response.text)
# 获取火车票价格
prices = data['prices']
# 打印火车票价格
for price in prices:
print(price)
```
请注意,上述代码仅为示例,实际的URL和数据结构可能会有所不同。您需要根据实际情况进行相应的修改。
相关问题
python爬取12306火车票信息
以下是使用Python爬取12306火车票信息的示例代码:
```python
import requests
# 获取所有城市英文代码
url = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9053"
print("正在获取数据。")
# 发送请求,获取返回的数据
res = requests.get(url)
data = str(res.content, encoding="utf8")
print(data)
```
这段代码使用requests库发送GET请求,获取12306网站上的城市英文代码数据。首先,我们需要指定URL链接,然后发送请求并获取响应的数据。最后,将获取到的数据转换为字符串并打印出来。
python 爬取网站机票价格
爬取网站机票价格需要用到 Python 的 requests 库和 BeautifulSoup 库。具体步骤如下:
1. 安装 requests 库和 BeautifulSoup 库。可以使用 pip 命令进行安装:
```python
pip install requests
pip install beautifulsoup4
```
2. 分析网页结构,找到需要爬取的数据。以携程网为例,搜索机票后得到的网页中,每个机票信息都包含在一个 class 为 `flight_item` 的 div 标签中,机票价格在标签内的 class 为 `base_price02` 的 span 标签中。
3. 编写 Python 程序,使用 requests 库发送 GET 请求获取网页内容,再使用 BeautifulSoup 库解析网页,找到需要的机票价格信息并输出。
示例代码如下:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://flights.ctrip.com/itinerary/oneway/sha-bkk?date=2022-01-01'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
items = soup.find_all('div', class_='flight_item')
for item in items:
price = item.find('span', class_='base_price02').text
print(price)
```
上述代码中,首先定义了需要爬取的网址和请求头。然后使用 requests 库发送 GET 请求获取网页内容。接着使用 BeautifulSoup 库解析网页,找到所有 class 为 `flight_item` 的 div 标签,遍历每个标签,找到其中的 class 为 `base_price02` 的 span 标签,获取机票价格并输出。
需要注意的是,爬取网站数据可能会涉及到法律风险,请遵守相关规定。