Python實(shí)現(xiàn)大數(shù)據(jù)收集至excel的思路詳解
一、在工程目錄中新建一個excel文件
二、使用python腳本程序?qū)⒛繕?biāo)excel文件中的列頭寫入,本文省略該部分的code展示,可自行網(wǎng)上查詢
三、以下code內(nèi)容為:實(shí)現(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)境下路徑
總結(jié)
以上所述是小編給大家介紹的Python實(shí)現(xiàn)大數(shù)據(jù)收集至excel的思路詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
- 在Python中利用Pandas庫處理大數(shù)據(jù)的簡單介紹
- 為什么入門大數(shù)據(jù)選擇Python而不是Java?
- python分塊讀取大數(shù)據(jù),避免內(nèi)存不足的方法
- python使用pandas處理大數(shù)據(jù)節(jié)省內(nèi)存技巧(推薦)
- Python如何處理大數(shù)據(jù)?3個技巧效率提升攻略(推薦)
- Python大數(shù)據(jù)之從網(wǎng)頁上爬取數(shù)據(jù)的方法詳解
- Python讀大數(shù)據(jù)txt
- 淺談用Python實(shí)現(xiàn)一個大數(shù)據(jù)搜索引擎
- Python實(shí)現(xiàn)的大數(shù)據(jù)分析操作系統(tǒng)日志功能示例
- Python大數(shù)據(jù)之網(wǎng)絡(luò)爬蟲的post請求、get請求區(qū)別實(shí)例分析
- Python(Pandas、Dask、PySpark等庫)在大數(shù)據(jù)處理中的學(xué)習(xí)心得
相關(guān)文章
python函數(shù)之任意數(shù)量的實(shí)參方式
這篇文章主要介紹了python函數(shù)之任意數(shù)量的實(shí)參方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
python GUI庫圖形界面開發(fā)之PyQt5 MDI(多文檔窗口)QMidArea詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5 MDI(多文檔窗口)QMidArea詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-03-03
Python編程實(shí)現(xiàn)二叉樹及七種遍歷方法詳解
這篇文章主要介紹了Python編程實(shí)現(xiàn)二叉樹及七種遍歷方法,結(jié)合實(shí)例形式詳細(xì)分析了Python二叉樹的定義及常用遍歷操作技巧,需要的朋友可以參考下2017-06-06
Flask框架學(xué)習(xí)筆記之表單基礎(chǔ)介紹與表單提交方式
這篇文章主要介紹了Flask框架學(xué)習(xí)筆記之表單基礎(chǔ)介紹與表單提交方式,結(jié)合實(shí)例形式分析了flask框架中表單的基本功能、定義、用法及表單提交的get、post方式使用技巧,需要的朋友可以參考下2019-08-08
python光學(xué)仿真通過菲涅耳公式實(shí)現(xiàn)波動模型
這篇文章主要介紹了python光學(xué)仿真通過菲涅耳公式實(shí)現(xiàn)波動模型的示例解析原理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10
python數(shù)據(jù)類型之間怎么轉(zhuǎn)換技巧分享
在本篇文章里小編給大家分享的是關(guān)于python數(shù)據(jù)類型之間怎么轉(zhuǎn)換實(shí)例以及小技巧內(nèi)容,有興趣的朋友們參考下。2019-08-08

