接收HTTP错误403:禁止CSV下载

问题描述 投票:1回答:1

我试图通过以下网址以编程方式访问csv:http://www.cmegroup.com/CmeWS/exp/voiProductDetailsViewExport.ctl?media=xls&tradeDate=20180627&reportType=F&productId=425

我已经通过两种方式尝试了这一点,一种是将URL传递给data_sheet = pd.read_csv(sheet_url)。尝试使用此方法时,我收到HTTP Error 403: Forbidden异常。

def get_sheet(self):
        # Accesses CME direct URL (at the moment...will add functionality for ICE later)
        # Gets sheet and puts it in dataframe
        #Returns dataframe sheet

        sheet_url = "http://www.cmegroup.com/CmeWS/exp/voiProductDetailsViewExport.ctl?media=xls&tradeDate="+str(self.date_of_report)+"&reportType="\
        + str(self.report_type)+"&productId=" + str(self.product)

        header = {
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }

        data_sheet = pd.read_csv(sheet_url)

        return data_sheet

我也试过假装是一个浏览器,认为该网站可能不允许直接调用csv,但后来我收到了Invalid file path or buffer object type: <class 'requests.models.Response'>异常

def get_sheet(self):
        # Accesses CME direct URL (at the moment...will add functionality for ICE later)
        # Gets sheet and puts it in dataframe
        #Returns dataframe sheet

        sheet_url = "http://www.cmegroup.com/CmeWS/exp/voiProductDetailsViewExport.ctl?media=xls&tradeDate="+str(self.date_of_report)+"&reportType="\
        + str(self.report_type)+"&productId=" + str(self.product)

        header = {
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }

        req = requests.get(url = sheet_url, headers = header)

        data_sheet = pd.read_csv(req)

        return data_sheet

我的最终目标是简单地在该URL处检索CSV并返回数据框。我错过了什么?

更新:我做了一些更多的摆弄,只是打印req,我得到了Response [200]的输出,我从HTTP文档中看到的意味着服务器正在接收我的信息。有谁知道问题是我是否直接访问存储csv的URL,通常,如果单击与该URL关联的按钮,它会自动下载该文件。在检查我的下载文件夹时,我没有看到该文件的任何下载。因此,虽然服务器可能正在接收有效请求,但我可能无法正确处理URL行为。有任何想法吗?

python pandas csv python-requests
1个回答
4
投票

您的代码有两个问题:

  1. 您正在将响应对象传递给pandas, 当你的实际csv数据在data_sheet = pd.read_csv(sheet_url)时,sheet_url.content
  2. pandas无法从csv读取stringpd.read_csv仅适用于文件对象。因此,要读取下载的内容,您需要使用字符串编写器创建文件来创建物理文件或使用io.StringIO(response.content.decode('utf-8'))

使用io模块的一个示例是:

import requests
import io
import pandas as pd

response = requests.get('http://samplecsvs.s3.amazonaws.com/SalesJan2009.csv')

file_object = io.StringIO(response.content.decode('utf-8'))
pd.read_csv(file_object)
© www.soinside.com 2019 - 2024. All rights reserved.