如何将api数据保存到csv文件中

时间:2019-07-15 17:27:14

标签: python-3.x

我正在尝试从外部API提取数据并将其保存到csv文件中,但是在保存时会遇到一些问题。

import requests 
import json 
import codecs 
import csv 

url =    'https://api-metrika.yandex.net/stat/v1/data.csv'
payloads={'metrics':['ym:s:visits','ym:s:users','ym:s:bounceRate'],
      'dimensions':['ym:s:<attribution>UTMSource','ym:s:<attribution>UTMMedium', 'ym:s:<attribution>UTMCampaign', 'ym:s:<attribution>UTMContent', 'ym:s:<attribution>UTMTerm'],
      'filters':"ym:s:<attribution>UTMSource=='mytarget'",
      'id':858663}
header = {'Authorization': 'OAuth AgAAASJHmAAWuxKyxoybOPkDfi3tt2AVH9ow',
      'Content-Type': 'application/x-yametrika+json'
      }
#here my extracted data in csv format
responce =   requests.get(url,headers=header, params=payloads)
decoded_data =codecs.decode(responce.text.encode(), 'utf-8-sig')
#here i am trying to save it
csv_file = open('csvmytarget.csv', 'w+', newline=None)
obj = csv.writer(csv_file, delimiter = ",", quotechar='"', quoting= csv.QUOTE_ALL )
obj.writerows(decoded_data)
csv_file.close()

运行脚本后,它创建的csv文件被误认为是

"
U
T
M

S
O
U
R
C
E
"
,
"
U
T
M
"

以此类推。我做错了

0 个答案:

没有答案