python爬取地铁路线矢量数据
时间: 2025-03-26 09:26:03 浏览: 33
### 地铁线路矢量数据的网页抓取及处理
为了实现地铁线路矢量数据的自动获取,可以采用Python编写脚本完成这一过程。此方法不仅适用于单个城市的数据收集,还能够扩展至更大范围内的铁路或轨道交通系统的矢量信息采集。
#### 准备工作
在开始之前,需安装必要的库来支持HTTP请求发送、HTML解析以及地理空间数据分析等功能:
```bash
pip install requests beautifulsoup4 geopandas shapely fiona osmnx
```
这些工具可以帮助更高效地定位并提取目标页面中的有效链接与文件资源。
#### 编写爬虫程序
下面是一个简单的例子展示如何构建一个基本框架用于从特定API接口或是静态网页中抽取所需的地图要素,并将其保存为Shapefile格式[^2]。
```python
import requests
from bs4 import BeautifulSoup
import json
import geopandas as gpd
from shapely.geometry import LineString, Point
def fetch_subway_data(city_code):
url = "https://restapi.amap.com/v3/subway/station?city={}&output=json&key=YOUR_API_KEY".format(
city_code)
response = requests.get(url)
if response.status_code != 200:
raise Exception('Failed to load page {}'.format(url))
data = response.json()
stations = []
for line in data['subways']:
coords = []
for station in line["stations"]:
latlng = (float(station['location'].split(',')[1]), float(station['location'].split(',')[0]))
coords.append(latlng)
# 添加车站点位
point = Point(*latlng[::-1])
stations.append({
'type': 'Feature',
'geometry': point,
'properties': {
'name': station['name'],
'line_name': line['name']
}
})
linestring = LineString(coords)
stations.append({
'type': 'Feature',
'geometry': linestring,
'properties': {'name': line['name']}
})
return stations
if __name__ == '__main__':
features = fetch_subway_data('上海')
df = gpd.GeoDataFrame.from_features(features)
output_file = './shanghai_subway.shp'
df.to_file(output_file, driver='ESRI Shapefile')
print(f'Successfully saved Shanghai subway lines into {output_file}')
```
这段代码通过调用高德开放平台提供的API服务获得指定城市(此处以上海为例)内所有地铁站的位置坐标及其所属路线名称等属性信息;接着利用`geopandas`库将上述结构化后的JSON对象转换成GeoDataFrame形式以便后续操作;最后导出为标准的空间数据交换格式——即Shapefiles。
请注意,在实际部署前应先注册成为开发者账号以获取合法访问令牌(`YOUR_API_KEY`),同时遵循服务商设定的各项条款限制条件。
阅读全文
相关推荐
















