如何爬取全國兩千多個城市的經緯度?其實找對了數據源就一點也不難。
哪些網站可能會有全國所有城市的經緯度呢?高德地圖?百度地圖?統計局?淘寶?……
這次我們來試試通過餓了么爬取:
import requests,csv,Geohash
url='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=0
list_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:
pass
for 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 中的內容后,成功!
拿到全國所有城市的經緯度以后,我們能做的還有很多,下期介紹~
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
