本文只做微信公众号测试用
一、功能
关注微信公众号 西安气象爱好者,发送通过高德地图分享的链接地址,格式为 http://surl.amap.com/xxxxxxxxxxxxx ,公众号将自动回复对应地点的经度和纬度,可获取自己定位位置的经纬度,也可搜索地图任意位置获取经纬度。
二、操作方法:
1、在高德地图APP上定位或者搜索地址,选择分享,按住下图红圈即可复制链接。
获取链接地址
2、将复制的链接发送给微信公众号“西安气象爱好者”,获取地址数据。
三、python代码:
1、高德地图链接解析:原理就是这个链接地址会经过302
跳转,跳转的中间地址包括了经度和纬度,只要通过requests
库获取到,再由正则表达式提取就可以。
(实际上,如果用浏览器打开链接,经纬度也会直接出现在最终的200
状态的地址中,但浏览器地址栏的地址最终会被js
代码替换掉,禁用js就不会被替换)
import re
import requests
def dd2dms(deg):
d = int(float(deg))
md = abs(float(deg) - d) * 60
m = int(md)
sd = (md - m) * 60
return '{:d}° {:d}′ {:.7f}″'.format(d, m, sd)
headers = {
"User-Agent": "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
"Referer": "https://www.amap.com"
}
def Locate(url_string):
amapUrl = r'^http://surl.amap.com/\w{13}$'
if re.match(amapUrl, url_string) is None:
return 'NOT FOUND'
try:
url_string = 'https://' + url_string[7:]
r = requests.head(url_string, stream=True, headers=headers)
realUrl = r.headers['Location']
posPattern = r'(\d{1,3}\.\d{6,20}),(\d{1,3}\.\d{6,20})'
jingdu = re.search(posPattern, realUrl).group(2)
# print(jingdu)
weidu = re.search(posPattern, realUrl).group(1)
# print(weidu)
result = '({0},{1})\r\n({2},{3})'.format(weidu, jingdu, dd2dms(weidu), dd2dms(jingdu))
return result
except BaseException as e:
print(e)
return 'NOT FOUND'
if __name__ == '__main__':
url_string = 'http://surl.amap.com/3U9wY_0957DEP'
print(Locate(url_string))
2、微信公众号自动回复
也是用python
来做微信公众号的后台接入,web.py
模块比较简单,写两个方法,一个接收一个回复。
GET:
def GET(self):
try:
data = web.input()
if len(data) == 0:
return "hello, this is handle view"
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
token = "xxxxxxxxxxx"
list1 = [token,timestamp,nonce]
list1.sort()
str_list1 = ''.join(list1)
print(str_list1)
sha1 = hashlib.sha1()
sha1.update(str_list1.encode('utf-8'))
hashcode = sha1.hexdigest()
print("handle/GET func: hashcode, signature: ", hashcode, signature)
if hashcode == signature:
return echostr
else:
return ""
except Exception as Argument:
return Argument
POST:
def POST(self):
str_xml = web.data()
xml = etree.fromstring(str_xml)
msgType = xml.find("MsgType").text
fromUser = xml.find("FromUserName").text
toUser = xml.find("ToUserName").text
#如果符合高德链接格式则返回经纬度,否则返回test+原字符串
if msgType == 'text':
getMsg=xml.find("Content").text.strip()
amapUrl = r'^http://surl.amap.com/\w{13}$'
if re.match(amapUrl, getMsg) is None:
content = "test"+ getMsg
else:
content=getLocate.Locate(getText)
render = web.template.render('templates/')
return render.reply_text(fromUser, toUser, int(time.time()), content)
elif msgType == 'image':
pass
else:
pass
网友评论