网站关键词选取的方法,旅游网站建设项目报告论文,做同业业务一般关注哪些网站,各种购物网站大全随着电动汽车的普及#xff0c;充电基础设施的建设变得至关重要。作为电动汽车领域的先驱#xff0c;特斯拉不仅在车辆技术创新上持续领先#xff0c;还积极构建广泛的充电网络#xff0c;以支持其不断增长的用户群体。为了提升用户体验和服务质量#xff0c;开发人员和数…
随着电动汽车的普及充电基础设施的建设变得至关重要。作为电动汽车领域的先驱特斯拉不仅在车辆技术创新上持续领先还积极构建广泛的充电网络以支持其不断增长的用户群体。为了提升用户体验和服务质量开发人员和数据分析师经常需要访问特斯拉充电桩的位置信息并将其集成到导航系统、移动应用或网站中。
本篇文章我们将探究GET请求的实际应用我们使用Python的requests库通过GET请求从特斯拉官方API获取充电桩位置信息深入讲解如何构造请求、解析响应数据以及实现数据可视化通过可视化分析来实现特斯拉在我国的分布情况。
特斯拉官方网址https://www.tesla.cn/
接下来就是数据获取部分先讲一下方法思路一共三个步骤
方法思路
获取所有location_id 列表另存为csv根据每个location_id 查询相关标签数据坐标转换BD09转WGS84
第一步我们先找到对应数据存储位置获取所有location_id 列表另存为csv 完整代码#运行环境 Python 3.11
import requests
import pandas as pd
from requests.adapters import HTTPAdapter, Retry# 设置请求参数和URL
url https://www.tesla.cn/cua-api/tesla-locations
params {translate: zh_CN,map: baidu,usetrt: true
}# 设置完整的请求头headers {Cookie: YOUR_COOKIE_HERE, # 替换为您的CookieUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36}# 创建会话并配置重试策略
session requests.Session()
retries Retry(total5, backoff_factor1, status_forcelist[500, 502, 503, 504])
adapter HTTPAdapter(max_retriesretries)
session.mount(https://, adapter)try:# 发送GET请求response session.get(url, paramsparams, headersheaders, timeout10)# 检查请求是否成功if response.status_code 200:# 解析JSON响应data response.json()# 检查响应是否为列表if isinstance(data, list):# 提取所有location_idlocation_ids [item.get(location_id) for item in data if location_id in item]# 创建DataFramedf pd.DataFrame(location_ids, columns[location_id])# 保存为CSV文件csv_filename tesla_locations.csvdf.to_csv(csv_filename, indexFalse, encodingutf-8-sig)print(f已成功保存 {len(location_ids)} 个location_id到文件: {csv_filename})else:print(API响应不是预期的列表格式)print(f响应内容: {response.text})else:print(f请求失败状态码: {response.status_code}, 响应内容: {response.text})except requests.exceptions.RequestException as e:print(f请求过程中发生错误: {e})
我们就会到一个全国所有特斯拉旗下的包括体验店和展厅、超级充电站、服务中心、目的地充电、钣喷中心的位置坐标的表格tesla_locations.csv 第二步我们发现点击一个任意图标就会生成新的一个链接在链接中我们就可以获得对应标签数据来看一下链接的规律不同点就是location_id的不同值我们通过遍历所有的location_id就可以获得所有的标签数据 完整代码#运行环境 Python 3.11
import requests
import pandas as pd
import json
from datetime import datetime
import time
import random
import mathdef bd09_to_wgs84(bd_lon, bd_lat):百度坐标系(BD-09)转WGS84坐标系x_pi 3.14159265358979324 * 3000.0 / 180.0x float(bd_lon) - 0.0065y float(bd_lat) - 0.006z math.sqrt(x * x y * y) - 0.00002 * math.sin(y * x_pi)theta math.atan2(y, x) - 0.000003 * math.cos(x * x_pi)wgs_lon z * math.cos(theta)wgs_lat z * math.sin(theta)return wgs_lon, wgs_lat# 读取已有的 CSV 文件
df pd.read_csv(D:\\data\\tesla_locations.csv)
locations_list []# 设置请求头headers {Cookie: YOUR_COOKIE_HERE, # 替换为您的CookieUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36}# 遍历CSV中的每个location_id
for index, row in df.iterrows():location_id row[location_id]# 构建请求的 URLurl fhttps://www.tesla.cn/cua-api/tesla-location?id{location_id}mapbaidu# 随机延时 1-3 秒delay random.uniform(1, 3)print(f等待 {delay:.2f} 秒...)time.sleep(delay)# 发送 GET 请求try:response requests.get(url, headersheaders)print(f正在处理第 {index 1}/{len(df)} 个位置ID: {location_id})if response.status_code 200:try:data response.json()# 获取百度坐标bd_lon data.get(longitude)bd_lat data.get(latitude)# 转换为WGS84坐标if bd_lon and bd_lat:wgs84_lon, wgs84_lat bd09_to_wgs84(bd_lon, bd_lat)else:wgs84_lon, wgs84_lat None, Nonelocation_info {location_id: data.get(location_id),title: data.get(title),address: data.get(address),city: data.get(city),province_state: data.get(province_state),country: data.get(country),bd_longitude: bd_lon, # 百度坐标bd_latitude: bd_lat, # 百度坐标wgs84_longitude: wgs84_lon, # WGS84坐标wgs84_latitude: wgs84_lat, # WGS84坐标postal_code: data.get(postal_code),directions_link: data.get(directions_link),location_type: data.get(location_type, []),functions_names: data.get(functions_names, [])}locations_list.append(location_info)print(f成功获取: {location_info[title]})except json.JSONDecodeError:print(fID {location_id} 的响应内容不是有效的JSON格式)else:print(f请求ID {location_id} 失败状态码: {response.status_code})except Exception as e:print(f处理ID {location_id} 时发生错误: {str(e)})# 保存结果
try:current_time datetime.now().strftime(%Y%m%d_%H%M%S)filename ftesla_locations_detail_{current_time}.csvdf_result pd.DataFrame(locations_list)df_result.to_csv(filename, indexFalse, encodingutf-8-sig)print(f\n成功保存 {len(locations_list)} 条数据到 {filename})
except Exception as e:print(f保存文件时发生错误: {str(e)})到这里数据就下载完成了我们就得到了一个完整的包括特斯拉充电桩位置及其其他标签的csv 第三步坐标系转换因为数据用的是百度坐标系BD09我们需要把转换成wgs84坐标系在argis上展示才不会偏移我们把csv的坐标列手动分列一下并把坐标从百度坐标系BD09转到WGS84批量转换工具地图坐标系批量转换 - 免费在线工具 (latlongconverter.online)这里在讲一个热知识目前国内主要有以下三种坐标
WGS84一种大地坐标系也是目前广泛使用的GPS全球卫星定位系统使用的坐标系
GCJ02又称火星坐标系是由中国国家测绘局制订的地理信息系统的坐标系统。由WGS84坐标系经加密后的坐标系
BD09百度地图所使用的坐标体系是在火星坐标系的基础上又进行了一次加密处理 文章仅用于分享个人学习成果与个人存档之用分享知识如有侵权请联系作者进行删除。所有信息均基于作者的个人理解和经验不代表任何官方立场或权威解读。