python爬虫之解析json-抓取饿了么外卖餐饮店数据
2017-06-02 本文已影响493人
chengcxy
解析json录制的视频 由于今天网络原因 没有测完和录制完成 可以跑每个城市1页的数据 明日公司有事 周六下午返回 先了解一下这个,后续代码视频会在群内发布。
饿了么城市经纬度数据得url请求找包 可以看这篇文章 掌握python爬虫对数据处理有用吗?
代码
#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import requests
import json
import string
from Geohash import geohash
#url是找包得到 通过找到所有城市经纬度 去构造新的url请求 解析出店铺信息
def get_city_data(url):
try:
html=requests.get(url,headers=headers).content
city_code=json.loads(html)
for code in city_code:
city_info=json.loads(html)[code]
for city in city_info:
city_id=city['id']
city_name=string.replace(city['name'],u'\u200b','')
abbr=city['abbr']
pinyin=city['pinyin']
latitude=city['latitude']
longitude=city['longitude']
#下面变量 原以为是构造新的url必备的参数 然并卵。。算是业余了解geohash算法 将经纬度转换为字符串编码
city_geohash=geohash.encode(latitude,longitude)
print code,city_name,pinyin,latitude,longitude,city_geohash
shop_url=base_url.format(str(latitude),str(longitude))
get_shop_data(shop_url)
except Exception as e:
print (u"get_city_data函数解析错误 错误为 %s" % e)
#解析jspn 数据 获取 店名 地址 电话 开张时间 人均消费 评分 配送费 平均送餐时间 是否支持开发票等数据 数据字段很多 我取了以店铺相关的数据
def get_shop_data(url):
print url
#可以将这个url 拷贝到bejson 这个网站 看返回的json字符串数据 取值
try:
html=requests.get(url).content
json_data=json.loads(html)
for item in json_data:
#综合评分
rating=item['rating']
regular_customer_count=item['regular_customer_count']
#人均消费
average_cost=string.replace(item['average_cost'], u'\xa5','') if item.has_key('average_cost') else u'无数据'
#店铺描述
description=item['description']
#五星好评数
rating_count=item['rating_count']
#营业时间
opening_hours=item['opening_hours'][0] if len(item['opening_hours'])>0 else u'未标注营业时间'
#近一月销量
recent_order_num=item['recent_order_num']
#是否提供发票
supports=item['supports'][0]['description'] if len(item['supports'])>0 and item['supports'][0].has_key('description') else u'无数据'
piecewise_agent_fee=string.replace(item['piecewise_agent_fee']['description'],u'\xa5','').replace('配送费','')
phone=item['phone']
address=item['address']
distance=item['distance']
name=string.replace(item['name'],u'\u200b','') if string.replace(item['name'],u'\u200b','') else string.replace(item['name'],u'\u200b','')
#平均送达时间
order_lead_time=item['order_lead_time']
print name,address,phone,order_lead_time,opening_hours,supports,rating,average_cost,regular_customer_count,piecewise_agent_fee
except Exception as e:
print ("get_shop_data函数解析错误 错误为 %s" % e)
if __name__ == '__main__':
#city_url_api 是通过谷歌浏览器 右键检查 找包 后续会录制视频
city_url_api='https://mainsite-restapi.ele.me/shopping/v1/cities'
#offset 是page数 1页24个商铺 每个城市的总商铺数量 原本可以取到 网络原因 周末完善一下
base_url='https://mainsite-restapi.ele.me/shopping/restaurants?extras%5B%5D=activities&latitude={}&longitude={}&offset=1&terminal=web'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
,
'Cookie':'ubt_ssid=p30hpd9qtvks5km570udkrfgxggc2kpo_2017-05-23; _utrace=e634c43b1397e782d72c0a5358afa4a8_2017-05-23'
}
get_city_data(city_url_api)