如何爬取全國兩千多個城市的經緯度?其實找對了數據源就一點也不難。
哪些網站可能會有全國所有城市的經緯度呢?高德地圖?百度地圖?統計局?淘寶?……
這次我們來試試通過餓了么爬?。?/p>
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 中的內容后,成功!
拿到全國所有城市的經緯度以后,我們能做的還有很多,下期介紹~
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。