溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python如何實現(xiàn)大數(shù)據(jù)收集至excel

發(fā)布時間:2021-03-24 10:22:11 來源:億速云 閱讀:195 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下Python如何實現(xiàn)大數(shù)據(jù)收集至excel,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

一、在工程目錄中新建一個excel文件

二、使用python腳本程序?qū)⒛繕?biāo)excel文件中的列頭寫入,本文省略該部分的code展示,可自行網(wǎng)上查詢

三、以下code內(nèi)容為:實現(xiàn)從接口獲取到的數(shù)據(jù)值寫入excel的整體步驟

       1、整體思路:

             (1)、根據(jù)每日調(diào)取接口的日期來作為excel文件中:列名為“收集日期”的值

             (2)、程序默認(rèn)是每天會定時調(diào)取接口并獲取接口的返回值并寫入excel中(我使用的定時任務(wù)是:linux下的contab)

             (3)、針對接口異常未正確返回數(shù)據(jù)時,使用特殊符號如:NA代替并寫入excel文件中(后期使用excel數(shù)據(jù)做分析時有用)

        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指標(biāo)值收集"""
  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"
      }
    }
    """替換請求參數(shù)中的開始日期"""
    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]
    """替換請求參數(shù)中的結(jié)束日期"""
    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指標(biāo)值收集"""
      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指標(biāo)值數(shù)據(jù)收集入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 # 獲取表格中已存在的數(shù)據(jù)的行數(shù)
  new_workbook = copy(workbook) # 將xlrd對象拷貝轉(zhuǎn)化為xlwt對象
  new_worksheet = new_workbook.get_sheet(0) # 獲取轉(zhuǎn)化后工作簿中的第一個表格
  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]) # 追加寫入數(shù)據(jù),注意是從i+rows_old行開始寫入
  new_workbook.save(basedir + "/data/collect_data_center.xls") # 保存工作簿
  print("adr指標(biāo)值---xls格式表格【追加】寫入數(shù)據(jù)成功!")

              3、從步驟2中的代碼可看出代碼整體分為3個部分:

                    (1)、組裝接口參數(shù);

                    (2)、調(diào)用接口將接口返回的結(jié)果集收集在list中;

                    (3)、將收集的結(jié)果寫入excel中并保存;

tips:windows與linux下excel的路徑格式需要區(qū)分下,以上代碼中的"/data/collect_data_center.xls"為linux環(huán)境下路徑

看完了這篇文章,相信你對“Python如何實現(xiàn)大數(shù)據(jù)收集至excel”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI