如何爬取全国两千多个城市的经纬度?其实找对了数据源就一点也不难。
哪些网站可能会有全国所有城市的经纬度呢?高德地图?百度地图?统计局?淘宝?……
这次我们来试试通过饿了么爬取:

import requests,csv,Geohashurl='https://www.ele.me/restapi/shopping/v1/cities'headers={ 'referer': 'https://www.ele.me/home/', 'user-agent': 'user-agent' #user-agent大家改成自己的哈}res=requests.get(url,headers=headers)res_dic=res.json()# print(type(jsonres))#爬一个城市试验一下行不行,不要一上来就搞个大的name=res_dic['A'][0]['name']print(name)#没问题,那就开始吧csv_file=open('城市经纬度.csv','w+',newline='',encoding='utf-8')writer=csv.writer(csv_file)list_head=['城市','纬度','经度','geohash编码']writer.writerow(list_head)m=0list_cities=[]list_range=['A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','W','X','Y','Z']for alp in list_range: for m in range(220): try: name=res_dic[alp][m]['name'] latitude=res_dic[alp][m]['latitude'] longitude=res_dic[alp][m]['longitude'] geohash=Geohash.encode(latitude,longitude) list_cities.append([name,latitude,longitude,geohash]) m=m+1 except IndexError: passfor row in list_cities: writer.writerow(row)csv_file.close()

有些同学可能安装了geohash,但是python3.7调不出来。
别着急,修改一下定义文件试试:

rename the package name to be geohash rather than Geohash and then change init.py to import from .geohash (with a dot in front of the module name) rather than from geohash, the package should work for Python 3.5.2.

按照这个方法修改文件名称和 init.py 中的内容后,成功!

拿到全国所有城市的经纬度以后,我们能做的还有很多,下期介绍~