首页 > 解决方案 > 将 resquest.content 转换为 Panda Dataframe python

问题描述

我请求从如下服务器登录和下载数据:

import pandas as pd
import requests
from io import StringIO
import json

url = "http://192.168.18.18/vicidial/call_report_export.php"

querystring = {"DB":"",
           "run_export":"1",
           "ivr_export":"",
           "query_date":"2019-10-22",
           "end_date":"2019-10-22",
           "date_field":"call_date",
           "header_row":"YES",
           "rec_fields":"NONE",
           "call_notes":"NO",
           "export_fields":"STANDARD",
           "campaign[]":["EdsnSTF","SuperED"],
           "SUBMIT":"SUBMIT",
           "campaign%5B%5D":["EdsnSTF","SuperED"]}

headers = {'Authorization': "Basic ZWs5NjAxNDoxMjUw",
           'Accept': "*/*",
           'Cache-Control': "no-cache",
           'Host': "192.168.18.18",
           'Accept-Encoding': "gzip, deflate",
           'Connection': "keep-alive",
           'cache-control': "no-cache"
           }

response = requests.get(url, headers=headers, params=querystring)

print(response.content)

响应的内容是:

b'call_date\tphone_number_dialed\tstatus\tuser\tfull_name\tcampaign_id\tvendor_lead_code\tsource_id\tlist_id\tgmt_offset_now\tphone_code\tphone_number\ttitle\tfirst_name\tmiddle_initial\tlast_name\taddress1\taddress2\taddress3\tcity\tstate\tprovince\tpostal_code\tcountry_code\tgender\tdate_of_birth\talt_phone\temail\tsecurity_phrase\tcomments\tlength_in_sec\tuser_group\talt_dial\trank\towner\tlead_id\tlist_name\tlist_description\tstatus_name\r\n

我无法将其转换为 python 中的数据框

标签: pythondataframe

解决方案


该响应仅看起来像响应的标题行。最后缺少 a '

它是 a bytes,因此您需要将其转换为 string content.decode(<encoding>)。编码可能是 UTF8,但也可以是 ASCII 或其他,具体取决于服务器。

然后用pandas.read_csv

pd.read_csv(StringIO(content.decode("utf8")), sep="\t")

你得到一个数据框


推荐阅读