温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用Python显示点过的外卖

发布时间:2021-11-20 15:28:43 来源:亿速云 阅读:174 作者:iii 栏目:编程语言

本篇内容主要讲解“怎么用Python显示点过的外卖”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用Python显示点过的外卖”吧!

通过手机&验证码登录自己的饿了么账号,成功之后会返回当前用户的user_id 和 登录Cookie。这两个信息为后续的请求提供必要的信息。

一开始访问订单,是这样的请求

h6.ele.me/restapi/bos/v2/users/26803312/orders?limit=8&offset=0

h6.ele.me/restapi/bos/v2/users/26803312/orders?limit=8&offset=8

h6.ele.me/restapi/bos/v2/users/26803312/orders?limit=8&offset=16

当继续下拉,出现"查看三个月前的外卖订单"按钮时,请求是这样的

h6.ele.me/restapi/bos/v2/users/26803312/old_orders?limit=8&from_time=

h6.ele.me/restapi/bos/v2/users/26803312/old_orders?limit=8&from_time=1557718107

from_time的值在上次请求的响应中可以看到:

怎么用Python显示点过的外卖

获取订单部分代码如下所示:

"""
 获取近3个月订单
"""
def get_new_order():
 num = 0
 while 1:
 # 偏移量
 offset = num * limit
 response = requests.get(url + f'?limit={limit}&offset={offset}', headers=headers, verify=False)
 resp_json = response.json()
 insert_mongo(resp_json)
 # 当响应订单数小于8时 跳出循环
 if len(resp_json) < 8:
 print('====================')
 break
 num += 1
"""
历史订单
"""
def history_order():
 from_time = ''
 while 1:
 response = requests.get(old_url + f'?limit={limit}&from_time={from_time}', headers=headers, verify=False)
 resp_json = response.json()
 from_time = resp_json['from_time']
 orders = resp_json['orders']
 # 经过测试,最后一个订单时,会在请求一次 响应为空
 if not orders:
 break
 insert_mongo(orders)

运行之后发现,这一年多的时间,光外卖竟然花费了1W多一点。爬取的数据可以选择将数据保存在csv文件中,也可以选择Mongod。这里我是插入到了MongoDB中。

def insert_mongo(resp_json):
 if not resp_json:
 return 
 for i in resp_json:
 # 菜品
 foods_group = i['basket']['group'][0]
 for j in foods_group:
 j['name'] = clean_data(j['name'])
 with open('foods_name_banxia.txt', 'a+') as f:
 f.write(j['name'] + '\n') # 将菜品写入文件,方便处理 # 配送费
 deliver_price = 0
 if 'deliver_fee' in i['basket'].keys():
 deliver_price = i['basket']['deliver_fee']['price']
 # 计算总花费
 global total
 total += i['total_amount']
 # 餐馆名
 restaurant_name = clean_data(i['restaurant_name'])
 with open('restaurant_name_banxia.txt', 'a+') as f:
 f.write(restaurant_name + '\n') # 记录餐馆名
 clo.insert_one({
 # 餐馆名
 'restaurant_name': restaurant_name,
 # 订单时间 formatted_created_at也可以取,但是近期的会显示xx小时之前
 'created_timestamp': time_convert(i['created_timestamp']),
 # 价格
 'total_amount': i['total_amount'],
 'foods_group': foods_group,
 'deliver_price': deliver_price
 })

在查看数据过程中,发现有的菜品和店铺名后面都有括号、或者方括号等特殊字符,里面的信息对我们来说也没有什么价值。可以简单的进行处理一下。

import re
def clean_data(data):
 a = re.sub("\\(.*?\\)|\\(.*?\\)|\\[.*?\\]|\\【.*?\\】|[A-Za-z0-9\@\\!\/]", "", data)
 a = a.replace('盒', '').replace('克', '').replace('个', '')\
 .replace('大份', '').replace('小份', '').replace('瓶', '').replace('组', '').replace(' ','')
 return a

这样,我们就将订单中的信息存在了数据库中。为了方便统计我将每个订单的菜品、以及餐馆名保存在了txt文件中。

可以通过wordcloud将餐品进行一个简单的可视化。

from random import randint
from matplotlib import pyplot as plt
from wordcloud import WordCloud
def random_color(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
 """Random Color func"""
 r = randint(30, 255)
 g = randint(30, 180)
 b = int(100.0 * float(randint(60, 120)) / 255.0)
 return "rgb({:.0f}, {:.0f}, {:.0f})".format(r, g, b)
content = open('foods_name.txt', encoding='utf-8').read()
wordcloud = WordCloud(background_color="white",
 width=1000,
 height=600,
 max_font_size=50,
 font_path='/System/Library/Fonts/PingFang.ttc', # 需要根据实际操作系统更换路径
 color_func=random_color).generate(content)
plt.imshow(wordcloud)
plt.axis("off")
plt.savefig('ele_wordcloud.png', format='png', dpi=200)

结果如下,有没有口味一样的同学呢?

怎么用Python显示点过的外卖

同样我们可以在终端通过sort命令去常光顾的餐馆进行统计。

  • sort -n 按照数值大小排序 升序

  • sort -r 降序排列

  • uniq -c 去重和统计

  • head -5 展示前5条

cat mao_out.txt | sort | uniq -c | sort -rg | head -5

结果如下 去的最多的是贡贡米线和张亮麻辣烫,统计范围内均光顾了14次。

Python3XXXAir:$ cat restaurant_name.txt |sort|uniq -c| sort -rg| head -5
 14 贡贡米线
 14 张亮麻辣烫
 13 京客隆
 11 沁香缘家常菜
 11 小巷麻辣香锅

可以通过matplotlib去统计一下每次定外卖的价格,并展示出来。

import pymongo
import matplotlib.pyplot as plt
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['ele']
clo = db['info_banxia']
result = clo.find({})
y = [i['total_amount'] for i in result]
x = [i for i in range(len(y))]
plt.ylabel("The unit price")
plt.xlabel("Times")
plt.plot(x, y)
plt.show()

结果图:

怎么用Python显示点过的外卖

可以看出,大部分价格在20 ~ 40 之间, 因为有时候为了满减,大部分都是跟同事朋友一起拼单。偶尔超过这个范围是买的水果、药等一些商品。

从这些数据中,我们同样得出,哪个月定外卖次数最为频繁。

# 该月定外卖次数
count = []
for i in data:
 ele_count = clo.count({'created_timestamp': re.compile(i)})
 count.append(ele_count)
plt.scatter(data, count)
plt.xticks(rotation=45)
plt.show()

怎么用Python显示点过的外卖

可以看出 18年3月定了22次外卖是最多的一次。11月份的时候定外卖次数最少。

到此,相信大家对“怎么用Python显示点过的外卖”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI