python爬取你想要的數(shù)據(jù)几缭,近期由于業(yè)務(wù)需求浙滤,用python爬取了高德地圖一些地點(diǎn)的數(shù)據(jù)茶行,爬出來(lái)數(shù)據(jù)大致情況如下:
image
下面是基本流程:
1躯概、注冊(cè)成為高德地圖API開發(fā)者,網(wǎng)址http://lbs.amap.com/(主要是獲取自己的keywords [注冊(cè)流程可以參考這個(gè)網(wǎng)址 https://lbs.amap.com/api/webservice/guide/create-project/get-key])畔师。
2.安裝網(wǎng)絡(luò)爬取第三方庫(kù)娶靡,主要是下面三個(gè)(pip install 安裝);
from urllib.parse import **quote**
from urllib import **request**
import **json**
3.創(chuàng)建網(wǎng)絡(luò)爬蟲爬取數(shù)據(jù)看锉,并對(duì)數(shù)據(jù)進(jìn)行解析(這塊就直接上代碼了)姿锭;
from urllib.parse import quote
from urllib import request
import json
# import xlwt
web_key = '**********' #自己高德的地圖的key密鑰
url = "http://restapi.amap.com/v3/place/text"
cityname = "南京" # 自己需要搜索城市
classfiled = "汽車站" # 自己需要搜索的目的地信息(比如想搜索醫(yī)院,直接替換成醫(yī)院即可)
i=0 # 爬取的頁(yè)面信息伯铣,i=2時(shí)即爬取第2頁(yè)的數(shù)據(jù)呻此。當(dāng) result['count']=0 時(shí)即此頁(yè)面已經(jīng)無(wú)信息,爬取所有數(shù)據(jù)時(shí)可以用此終止循環(huán)
req_url = **url** + "?key=" + **web_key** + '&extensions=all&keywords=' + quote(**classfiled**) + '&city=' + quote(**cityname**) + '&citylimit=true' + '&offset=25' + '&page=' + **str( i) **+ '&output=json'
data = ''
f=request.urlopen(req_url)
data = f.read()
data = data.decode('utf-8')
result=json.loads(data)
# print(result['count']) # 等于0時(shí)腔寡,即代表此頁(yè)面已經(jīng)無(wú)信息
result['pois'][0] #顯示數(shù)據(jù)記錄格式
處理過(guò)會(huì)趾诗,基本的網(wǎng)頁(yè)信息就出來(lái)了
image
以上的數(shù)據(jù)是以字典的形式打印出來(lái)的,把自己需要獲取的字段提出出來(lái)就可以了:
for i in range(len(result['pois'])):
print('名稱:',result['pois'][i]['name']
,'\n類型:',result['pois'][i]['type']
,'\n省份:',result['pois'][i]['pname']
,'\n城市:',result['pois'][i]['cityname']
,'\n地區(qū):',result['pois'][i]['adname']
,'\n鄉(xiāng)鎮(zhèn):',result['pois'][i]['business_area']
,'\n詳細(xì)地址:',result['pois'][i]['address']
,'\n經(jīng)緯度:',result['pois'][i]['location']
,'\n圖片鏈接:',result['pois'][i]['photos'][0]['url']
,'\n'
)
部分?jǐn)?shù)據(jù)結(jié)果如下:
image