Python实现大数据收集至excel的思路详解


Posted in Python onJanuary 03, 2020

一、在工程目录中新建一个excel文件

二、使用python脚本程序将目标excel文件中的列头写入,本文省略该部分的code展示,可自行网上查询

三、以下code内容为:实现从接口获取到的数据值写入excel的整体步骤

       1、整体思路:

             (1)、根据每日调取接口的日期来作为excel文件中:列名为“收集日期”的值

             (2)、程序默认是每天会定时调取接口并获取接口的返回值并写入excel中(我使用的定时任务是:linux下的contab)

             (3)、针对接口异常未正确返回数据时,使用特殊符号如:NA代替并写入excel文件中(后期使用excel数据做分析时有用)

        2、完整代码如下:

import requests, xlrd, os, sys, urllib3
from datetime import date, timedelta
from xlutils.copy import copy
basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(basedir)
from lib.mysqldb import mysqldb
from lib.public_methods import test_login
def collect_data():
  """test_rooms.test_kpi卡片下:adr指标值收集"""
  get_all_code_sql = 'select DISTINCT test_code from test_info WHERE open_flag = 1'
  test_code_all = mysqldb("test_data").selectsql(get_all_code_sql)
  test_code_list = []
  adr_insert_data_list = []
  yesterday = (date.today() + timedelta(days=-1)).strftime("%Y-%m-%d")
  adr_insert_data_list.append(yesterday)
  for j in range(len(test_code_all)):
    test_code_list.append(test_code_all[j]["test_code"])
  for m in range(len(test_code_list)):
    url = "https://www.baidu.com/test/api/data/query.json"
    header = {
      "Content-Type": "application/json;charset=UTF-8",
      "Cookie": str(test_login())
    }
    param = {
      "code": "test_rooms.test_kpi",
      "page": 1,
      "pageSize": 1000,
      "params": {
        "start_date_year": "2019",
        "start_date_month": "9",
        "start_date_day": "16",
        "end_date_year": "2019",
        "currency_type": "usd",
        "end_date_day": "16",
        "end_date_month": "9",
        "tests": "test_001"
      }
    }
    """替换请求参数中的开始日期"""
    param["params"]["start_date_year"] = str(yesterday).split("-")[0]
    param["params"]["start_date_month"] = str(yesterday).split("-")[1]
    param["params"]["start_date_day"] = str(yesterday).split("-")[2]
    """替换请求参数中的结束日期"""
    param["params"]["end_date_year"] = param["params"]["start_date_year"]
    param["params"]["end_date_month"] = param["params"]["start_date_month"]
    param["params"]["end_date_day"] = param["params"]["start_date_day"]
    param["params"]["tests"] = test_code_list[m]
    urllib3.disable_warnings()
    result = requests.post(url=url, headers=header, json=param, verify=False).json()
    if str(result["data"]["data"]) != "None":
      """adr指标值收集"""
      indicatorList = result["data"]["data"]["test_indicator_list"]
      test_actualorLast_Forecast = result["data"]["data"]["test_actual"]
      new_indicator_actualvalue = {}
      i = 0
      while i < len(indicatorList):
        dit = {indicatorList[i]: test_actualorLast_Forecast[i]}
        new_indicator_actualvalue.update(dit)
        i += 1
      if str(new_indicator_actualvalue["adr"]) == "--":
        adr_value_result = "NA"
        adr_insert_data_list.append(adr_value_result)
      else:
        adr_value_result = new_indicator_actualvalue["adr"]
        adr_insert_data_list.append(adr_value_result)
    else:
      adr_value_result = "NA"
      adr_insert_data_list.append(adr_value_result)
  """adr指标值数据收集入excel路径"""
  workbook = xlrd.open_workbook(basedir + "/data/collect_data_center.xls") # 打开工作簿
  sheets = workbook.sheet_names() # 获取工作簿中的所有表格
  worksheet = workbook.sheet_by_name(sheets[0]) # 获取工作簿中所有表格中的的第一个表格
  rows_old = worksheet.nrows # 获取表格中已存在的数据的行数
  new_workbook = copy(workbook) # 将xlrd对象拷贝转化为xlwt对象
  new_worksheet = new_workbook.get_sheet(0) # 获取转化后工作簿中的第一个表格
  for i in range(0, 1):
    for j in range(0, len([adr_insert_data_list][i])):
      new_worksheet.write(i + rows_old, j, [adr_insert_data_list][i][j]) # 追加写入数据,注意是从i+rows_old行开始写入
  new_workbook.save(basedir + "/data/collect_data_center.xls") # 保存工作簿
  print("adr指标值---xls格式表格【追加】写入数据成功!")

              3、从步骤2中的代码可看出代码整体分为3个部分:

                    (1)、组装接口参数;

                    (2)、调用接口将接口返回的结果集收集在list中;

                    (3)、将收集的结果写入excel中并保存;

tips:windows与linux下excel的路径格式需要区分下,以上代码中的"/data/collect_data_center.xls"为linux环境下路径

总结

以上所述是小编给大家介绍的Python实现大数据收集至excel的思路详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Python 相关文章推荐
Python Web框架Flask中使用新浪SAE云存储实例
Feb 08 Python
python实现mysql的单引号字符串过滤方法
Nov 14 Python
Python面向对象编程基础解析(二)
Oct 26 Python
Python3用tkinter和PIL实现看图工具
Jun 21 Python
pycharm 在windows上编辑代码用linux执行配置的方法
Oct 27 Python
使用pandas实现csv/excel sheet互相转换的方法
Dec 10 Python
基于python3监控服务器状态进行邮件报警
Oct 19 Python
Python中os模块功能与用法详解
Feb 26 Python
基于python tkinter的点名小程序功能的实例代码
Aug 22 Python
python对 MySQL 数据库进行增删改查的脚本
Oct 22 Python
pycharm无法导入lxml的解决办法
Mar 31 Python
Python 全局空间和局部空间
Apr 06 Python
Python如何基于rsa模块实现非对称加密与解密
Jan 03 #Python
PyTorch的自适应池化Adaptive Pooling实例
Jan 03 #Python
pytorch torch.nn.AdaptiveAvgPool2d()自适应平均池化函数详解
Jan 03 #Python
pytorch AvgPool2d函数使用详解
Jan 03 #Python
使用pyhon绘图比较两个手机屏幕大小(实例代码)
Jan 03 #Python
Python基础之函数原理与应用实例详解
Jan 03 #Python
对Pytorch中Tensor的各种池化操作解析
Jan 03 #Python
You might like
Syphon 秘笈
2021/03/03 冲泡冲煮
上海地方志办公室-上海电子仪表工业志
2021/03/04 无线电
关于shopex同步ucenter的redirect问题,导致script不运行
2013/04/10 PHP
php生成图形(Libchart)实例
2013/11/06 PHP
PHP两种去掉数组重复值的方法比较
2014/06/19 PHP
微信公众平台DEMO(PHP)
2016/05/04 PHP
完美利用Yii2微信后台开发的系列总结
2016/07/18 PHP
php出租房数据管理及搜索页面
2017/05/23 PHP
php 比较获取两个数组相同和不同元素的例子(交集和差集)
2019/10/18 PHP
动态添加option及createElement使用示例
2014/01/26 Javascript
基于jquery实现表格无刷新分页
2016/01/07 Javascript
用js读写cookie的简单方法(推荐)
2016/08/08 Javascript
JavaScript代码里的判断小结
2016/08/22 Javascript
基于jQuery的checkbox全选问题分析
2016/11/18 Javascript
Bootstrap导航条可点击和鼠标悬停显示下拉菜单
2016/11/25 Javascript
javascript中call()、apply()的区别
2019/03/21 Javascript
vue实现移动端省市区选择
2019/09/27 Javascript
微信小程序自定义tabbar custom-tab-bar 6s出不来解决方案(cover-view不兼容)
2019/11/01 Javascript
[40:53]完美世界DOTA2联赛PWL S3 Magma vs DLG 第二场 12.18
2020/12/20 DOTA
python中stdout输出不缓存的设置方法
2014/05/29 Python
Win7上搭建Cocos2d-x 3.1.1开发环境
2014/07/03 Python
浅谈python中截取字符函数strip,lstrip,rstrip
2015/07/17 Python
Python实现全角半角字符互转的方法
2016/11/28 Python
pygame加载中文名mp3文件出现error
2017/03/31 Python
Python中元组,列表,字典的区别
2017/05/21 Python
django使用html模板减少代码代码解析
2017/12/12 Python
python 统计列表中不同元素的数量方法
2018/06/29 Python
Django添加sitemap的方法示例
2018/08/06 Python
对python判断ip是否可达的实例详解
2019/01/31 Python
Python字典遍历操作实例小结
2019/03/05 Python
Python中使用pypdf2合并、分割、加密pdf文件的代码详解
2019/05/21 Python
阿联酋航空官方网站:Emirates
2017/10/17 全球购物
卡西欧G-SHOCK英国官网: 防水防震手表
2018/01/08 全球购物
工程专业毕业生自荐信范文
2013/12/25 职场文书
2014年教师业务学习材料
2014/05/12 职场文书
2014年国庆晚会主持词
2014/09/19 职场文书