python解析網(wǎng)頁(yè)上的json數(shù)據(jù)并保存到EXCEL
安裝必要的庫(kù)
import requests import pandas as pd import os import sys import io import urllib3 import json
測(cè)試數(shù)據(jù)
網(wǎng)頁(yè)上的數(shù)據(jù)結(jié)構(gòu)如下
{
"success": true,
"code": "CIFM_0000",
"encode": null,
"message": "ok",
"url": null,
"total": 3,
"items": [
{
"summaryDate": "20240611",
"summaryType": "naturalDay",
"workday": true,
"newCustNum": 1,
"haveCustNum": 1691627,
"newAccountNum": 2,
"haveAccountNum": 1692934,
"totalShare": 4947657341.69,
"netCash": -3523387.25,
"yield": 0.01386
},
{
"summaryDate": "20240612",
"summaryType": "naturalDay",
"workday": true,
"newCustNum": 5,
"haveCustNum": 1672766,
"newAccountNum": 5,
"haveAccountNum": 1674071,
"totalShare": 4927109080.29,
"netCash": -20735233.55,
"yield": 0.01387
},
{
"summaryDate": "20240613",
"summaryType": "naturalDay",
"workday": true,
"newCustNum": 4,
"haveCustNum": 1662839,
"newAccountNum": 5,
"haveAccountNum": 1664146,
"totalShare": 4927405885.59,
"netCash": 110659.8,
"yield": 0.01389
}
],
"data": null,
"info": null
}
詳細(xì)邏輯代碼
import requests
import pandas as pd
import os
import sys
import io
import urllib3
import json
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
url = "https://ip/ma/web/trade/dailySummary?startDate={pi_startdate}&endDate={pi_enddate}"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"Accept-Language": "zh-CN,zh;q=0.9",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0",
}
def save_data(data, columns, excel_path, sheet_name):
df = pd.DataFrame(data, columns=columns)
if not os.path.exists(excel_path):
df.to_excel(excel_path, sheet_name=sheet_name, index=False)
else:
with pd.ExcelWriter(excel_path, engine='openpyxl', mode='a') as writer:
df.to_excel(writer, sheet_name=sheet_name, index=False)
def json2list(response_text):
# 把json數(shù)據(jù)轉(zhuǎn)化為python用的類(lèi)型
json_dict = json.loads(response_text)
src_total = json_dict["total"]
print("src_total: {}".format(src_total))
items = json_dict["items"]
excel_columns = ['summaryDate',
'summaryType',
'workday',
'newCustNum',
'haveCustNum',
'newAccountNum',
'haveAccountNum',
'totalShare',
'netCash',
'yield'
]
excel_data = []
# 使用XPath定位元素并打印內(nèi)容
for item in items:
excel_row_data = []
for column_index in range(len(excel_columns)):
data = str(item[excel_columns[column_index]])
if excel_columns[column_index] == 'workday':
data = str(0 if data == "False" else 1)
excel_row_data.append(data)
excel_data.append(excel_row_data)
trg_total = len(excel_data)
# 稽核
print("trg_total: {}".format(trg_total))
vn_biasval = trg_total - src_total
if vn_biasval != 0:
print("This audit-rule is not passed,diff: {}".format(vn_biasval))
exit(-1)
else:
print("This audit-rule is passed,diff: {}".format(vn_biasval))
return excel_columns, excel_data
if __name__ == '__main__':
try:
excel_path = "C:/xxx/temp/ylb_dailySummary_{pi_startdate}_{pi_enddate}.xlsx"
sheet_name = 'result_data'
pi_startdate = 20240611
pi_enddate = 20240613
excel_path = excel_path.format(pi_startdate=pi_startdate, pi_enddate=pi_enddate)
url = url.format(pi_startdate=pi_startdate, pi_enddate=pi_enddate)
print("url:{}".format(url))
print("excel_path:{}".format(excel_path))
response_text = requests.get(url, headers=headers, timeout=(21, 300), verify=False).content.decode("utf8")
excel_columns, excel_data = json2list(response_text)
print("=================excel_columns=======================")
print(excel_columns)
print("=================excel_data==========================")
for x in excel_data:
print(x)
print("=====================================================")
# 文件存在,則刪除
if os.path.exists(excel_path):
os.remove(excel_path)
# 保存文件
save_data(excel_data, excel_columns, excel_path, sheet_name)
print("save_data is end.")
except Exception as e:
print("[ERROR]:" + str(e))
exit(-1)
代碼解析
1.請(qǐng)求頭
構(gòu)造請(qǐng)求頭
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
url = "https://ip/ma/web/trade/dailySummary?startDate={pi_startdate}&endDate={pi_enddate}"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"Accept-Language": "zh-CN,zh;q=0.9",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0",
}
2.數(shù)據(jù)保存到excel
如果excel已經(jīng)存在,那么則會(huì)將數(shù)據(jù)追加到excel中
def save_data(data, columns, excel_path, sheet_name):
df = pd.DataFrame(data, columns=columns)
if not os.path.exists(excel_path):
df.to_excel(excel_path, sheet_name=sheet_name, index=False)
else:
with pd.ExcelWriter(excel_path, engine='openpyxl', mode='a') as writer:
df.to_excel(writer, sheet_name=sheet_name, index=False)
解析json數(shù)據(jù)獲取字段名稱(chēng)以及對(duì)應(yīng)的數(shù)據(jù)list列表
def json2list(response_text):
# 把json數(shù)據(jù)轉(zhuǎn)化為python用的類(lèi)型
json_dict = json.loads(response_text)
src_total = json_dict["total"]
print("src_total: {}".format(src_total))
items = json_dict["items"]
excel_columns = ['summaryDate',
'summaryType',
'workday',
'newCustNum',
'haveCustNum',
'newAccountNum',
'haveAccountNum',
'totalShare',
'netCash',
'yield'
]
excel_data = []
# 使用XPath定位元素并打印內(nèi)容
for item in items:
excel_row_data = []
for column_index in range(len(excel_columns)):
data = str(item[excel_columns[column_index]])
if excel_columns[column_index] == 'workday':
data = str(0 if data == "False" else 1)
excel_row_data.append(data)
excel_data.append(excel_row_data)
trg_total = len(excel_data)
# 稽核
print("trg_total: {}".format(trg_total))
vn_biasval = trg_total - src_total
if vn_biasval != 0:
print("This audit-rule is not passed,diff: {}".format(vn_biasval))
exit(-1)
else:
print("This audit-rule is passed,diff: {}".format(vn_biasval))
return excel_columns, excel_data
3.測(cè)試方法入口
if __name__ == '__main__':
測(cè)試結(jié)果
會(huì)生成ylb_dailySummary_20240611_20240613.xlsx文件

以上就是python解析網(wǎng)頁(yè)上的json數(shù)據(jù)并保存到EXCEL的詳細(xì)內(nèi)容,更多關(guān)于python解析網(wǎng)頁(yè)json數(shù)據(jù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python 找出英文單詞列表(list)中最長(zhǎng)單詞鏈
這篇文章主要介紹了Python 找出英文單詞列表(list)中最長(zhǎng)單詞鏈,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Python使用BeautifulSoup和Scrapy抓取網(wǎng)頁(yè)數(shù)據(jù)的具體教程
在當(dāng)今信息爆炸的時(shí)代,數(shù)據(jù)無(wú)處不在,如何有效地抓取、處理和分析這些數(shù)據(jù)成為了許多開(kāi)發(fā)者和數(shù)據(jù)科學(xué)家的必修課,本篇博客將深入探討如何使用Python中的兩個(gè)強(qiáng)大工具:BeautifulSoup和Scrapy來(lái)抓取網(wǎng)頁(yè)數(shù)據(jù),需要的朋友可以參考下2025-01-01
Python使用Matplotlib進(jìn)行圖案填充和邊緣顏色分離的三種方法
Matplotlib是Python中功能強(qiáng)大的繪圖庫(kù),允許廣泛的自定義選項(xiàng),一個(gè)常見(jiàn)的要求是分離出圖中的圖案填充和邊緣顏色,默認(rèn)情況下,Matplotlib中的填充顏色與邊緣顏色相關(guān)聯(lián),但有一些方法可以獨(dú)立自定義這些顏色,本文將深入研究如何實(shí)現(xiàn)這一點(diǎn)的技術(shù)細(xì)節(jié),并提供分步說(shuō)明和示例2025-01-01
Python使用POP3和SMTP協(xié)議收發(fā)郵件的示例代碼
這篇文章主要介紹了Python使用POP3和SMTP協(xié)議收發(fā)郵件的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
Python?Poetry實(shí)現(xiàn)高效依賴(lài)管理的新手指南
這篇文章主要為大家詳細(xì)介紹了Python如何使用Poetry實(shí)現(xiàn)高效依賴(lài)管理,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-05-05
python關(guān)于調(diào)用函數(shù)外的變量實(shí)例
今天小編就為大家分享一篇python關(guān)于調(diào)用函數(shù)外的變量實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
python 裝飾器帶參數(shù)和不帶參數(shù)步驟詳解
裝飾器是Python語(yǔ)言中一種特殊的語(yǔ)法,用于在不修改原函數(shù)代碼的情況下,為函數(shù)添加額外的功能或修改函數(shù)的行為,這篇文章主要介紹了python裝飾器帶參數(shù)和不帶參數(shù)的相關(guān)知識(shí),需要的朋友可以參考下2024-05-05

