一、TinyUrl和Vgd
使用场景:
1、巡线工作,使用百度地图的api,将地点的经纬度信息放到百度api上,实现在浏览器上打开百度地图,定位到具体的地点。(有些地点,通过地址信息误差很大)
例子:组合起来,url很长
2、使用短链接系统,实现将长链接转成短链接
代码:
import requests
import json
class ShortUrl:
# 注意
NOTE = "当前系统中存储的经纬度是百度坐标系:bd09"
# 短链接的api接口
URL_LIST = [
{
"url": "http://tinyurl.com/api-create.php",
"url_type": "tinyurl",
"access_key": None,
},
{
"url": "https://v.gd/create.php",
"url_type": "v.gd",
"access_key": None,
},
]
# 百度地图api地址
BAIDU_URL = "https://api.map.baidu.com/marker"
def __init__(self, lon, lat, title, content="线路告警位置"):
"""
Args:
lon: 纬度
lat: 经度
title: 地址名
content: 地址描述描述
"""
# 待转换的长地址
self.long_url = f"{self.BAIDU_URL}?location={lon},{lat}&title={title}&content={content}&output=html"
def _get_short_url(self, url: str, url_type: str, access_key=None) -> [str, bool]:
"""
Args:
url: 提供短链接生成的网址
access_key: 该厂商需要的access_key
url_type: 厂商的类型,不同厂商的api接口参数不一样,提供不一样的代码段
Return:
url 或 False
"""
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'
headers = {'User-Agent': user_agent}
timeout = 30
try:
if url_type == "tinyurl":
params = {
'url': self.long_url,
}
response = requests.get(url,params=params,headers=headers,timeout=timeout)
return response.text
elif url_type == "v.gd":
params = {
'format': 'json',
'url': self.long_url,
}
f_desc = requests.get(url, params=params, headers=headers,timeout=timeout)
response = json.loads(f_desc.text)
return response.get('shorturl',False)
else:
raise Exception("不存在的短链接提供厂商,请添加该厂商的数据")
except Exception as e:
print('报错了')
return False
def main(self):
for dic in self.URL_LIST:
url = dic.get("url")
access_key = dic.get("access_key")
url_type = dic.get("url_type")
result = self._get_short_url(
url=url,
url_type=url_type,
access_key=access_key,
)
if isinstance(result, str):
return result
else:
# 生成短链接失败,直接返回原来的长url
return self.long_url
if __name__ == "__main__":
lon = "23.0534260666666"
lat = "113.40712125"
title = "大学城华工南路(华南理工大学C2号楼对面)"
# 使用例子
obj = ShortUrl(lon=lon, lat=lat, title=title)
short_url = obj.main()
print(short_url, "生成的短链接")