python爬取12306火车票信息
时间: 2023-12-26 22:27:46 浏览: 56
以下是使用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爬取12306网页
以下是一个示例代码,用于爬取12306网站的火车票信息:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头,模拟浏览器访问
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'
}
# 构造请求url
url = 'https://kyfw.12306.cn/otn/leftTicket/init'
# 带上请求头发送请求
response = requests.get(url, headers=headers)
# 使用BeautifulSoup解析页面
soup = BeautifulSoup(response.text, 'html.parser')
# 找到车站名称下拉框的所有选项
station_list = soup.select('#fromStation option')
# 打印所有车站的名称和对应的值
for station in station_list:
print(station.text, station['value'])
```
这个示例代码只是演示了如何获取车站名称下拉框的所有选项。如果你想获取火车票信息,需要构造带有查询参数的url,并发送请求获取相应的页面。具体可以参考12306网站的API文档。
小白教程:Python爬取铁路12306
铁路12306是中国铁路客户服务中心的官方网站,提供火车票购买、退票、查询等服务。如果你想使用Python爬取铁路12306的相关信息,你可以使用以下步骤:
1. 导入所需的模块:
```python
import requests
from bs4 import BeautifulSoup
import csv
```
2. 创建一个函数来检查链接是否可用:
```python
def check_link(url):
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
print('无法链接服务器!!!')
```
3. 创建一个函数来爬取铁路12306的数据:
```python
def get_contents(ulist, rurl):
soup = BeautifulSoup(rurl, 'html.parser')
# 根据具体的网页结构,使用BeautifulSoup提取所需的数据
# 并将数据存入ulist中
```
4. 创建一个函数来保存爬取的数据到CSV文件中:
```python
def save_contents(urlist):
try:
with open("data.csv", 'w', newline='') as f:
writer = csv.writer(f)
# 根据ulist的数据结构,将数据写入CSV文件中
except:
pass
```
5. 创建一个main函数来执行上述函数:
```python
def main():
urli = []
url = "http://www.maigoo.com/news/463071.html"
rs = check_link(url)
get_contents(urli, rs)
save_contents(urli)
```
这样,你就可以使用Python爬取铁路12306的相关信息了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)