0
点赞
收藏
分享

微信扫一扫

Python爬虫系列之三:根据名称爬取经纬度信息并Geohash编码


1 开发场景

  • 安装geohash模块并根据经纬度计算geohash值.
  • 爬取某些名称(地名)的经纬度等信息.
  • 开发语言及工具
  • Python 2
  • Anaconda
  • ​​mzgeohash​​
  • 安装包(tar.gz)下载 / 安装
  • ​​Link 1​​
  • 源码下载 / 安装
  • ​​Link 2​​
  • 注意:
  • 个人尝试,mzgeohash支持Python 2, Python 3 下会提示语法错误. 为了便于使用,开发均在Python 2 内核下完成.

2 详细描述

  • 基于 Python、通过百度API,爬取对应地名的经纬度等信息 .
  • 通过Python中​​Geohash​​ 模块,依据经纬度计算对应名称的 geohash 值 .

3 具体代码

# coding: utf-8

# ## 主要实现
# - 批量查询位置点 经纬度等信息
# - 经纬度转换为 geohash块

# ### Note
# - 查询位置列表, 需<font color=#FF1953>提前提供</font>

# In[5]:

city_lis=['北京', '上海', '郑州']


# ### 获取位置地点经纬度等信息
# - 获取经纬度等信息
# - 计算 geohash

# In[6]:

import pandas as pd
import mzgeohash
import urllib2
import urllib
import json


# In[23]:

'''
根据位置名称,获取经纬度等信息
'''
def get_metas_from_baidu(city):
metas={}
metas['key']='f247cdb592eb43ebac6ccd27f796e2d2'
metas['address']=city # 城市名称

data=urllib.urlencode(metas)
url='http://api.map.baidu.com/geocoder?output=json&'+urllib.urlencode(metas)
# 注释 url='http://api.map.baidu.com/geocoder?'+urllib.urlencode(metas)+'&output=json'
unicode_s=urllib2.urlopen(url)

return json.loads(unicode_s.read())

city_meta_lis=[] # 计算 geohash 编码并存储
for city in city_lis:
tmp=get_metas_from_baidu(city)
latitude=tmp['result']['location']['lat']
longitude=tmp['result']['location']['lng']
t_geohash=mzgeohash.encode((longitude,latitude)) # 使用mzgeohash 计算geohash
city_meta_lis.append([city,latitude,longitude,t_geohash]) # 存储


# In[24]:

# 格式化输出
df=pd.DataFrame(city_meta_lis, columns=['city','latitude','longitude','geohash'])
df

4 数据结果

  • 位置名称(地名)经纬度、geohash值等数据结果:
  • Python爬虫系列之三:根据名称爬取经纬度信息并Geohash编码_爬虫

5 参考文章

  • ​​百度地图 API 介绍(Geocoding API,推荐!)​​
  • 主要包含以下4个部分:
  • 接口功能
  • 接口参数
  • 返回数据说明
  • 接口示例
  • ​​百度地图WEB 服务API接口说明(推荐!)​​

6 问题总结

  • INVALID_PARAMETERS
  • 请求路径中包含非法参数
    ​​​{
    "results":[ ] ,
    "status" : "INVALID_PARAMETERS"
    }​
  • 解决方法
  • 对比 被注释掉的URL与 当前URL, 变更参数位置测试API是否能成功访问。
  • ​​Geocoding API v1.0​​

7 脚本下载

  • ​​lng_lat_2_geohash_two_way.ipynb​​


举报

相关推荐

0 条评论