请使用python爬虫火车票信息
时间: 2023-05-20 09:07:04 浏览: 65
可以使用Python中的requests和BeautifulSoup库来爬取火车票信息。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://kyfw.12306.cn/otn/leftTicket/init'
params = {
'linktypeid': 'dc',
'fs': '北京,BJP',
'ts': '上海,SHH',
'date': '2022-01-01',
'flag': 'N,N,Y'
}
response = requests.get(url, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
train_list = soup.select('#queryLeftTable tr')[1:]
for train in train_list:
train_info = train.select('td')
train_number = train_info[0].text.strip()
start_station = train_info[1].text.strip()
end_station = train_info[2].text.strip()
start_time = train_info[3].text.strip()
end_time = train_info[4].text.strip()
duration = train_info[5].text.strip()
print(train_number, start_station, end_station, start_time, end_time, duration)
```
这段代码会爬取12306网站上北京到上海的2022年1月1日的火车票信息,并输出火车车次、起点站、终点站、出发时间、到达时间和历时。