使用 Python 下载 Kaggle 数据集

Posted

技术标签:

【中文标题】使用 Python 下载 Kaggle 数据集【英文标题】:Download Kaggle Dataset by using Python 【发布时间】:2018-08-29 10:15:00 【问题描述】:

我尝试使用 python 下载kaggle dataset。但是我在使用 request 方法时遇到了问题,下载的输出 .csv 文件是损坏的 html 文件。

import requests

# The direct link to the Kaggle data set
data_url = 'https://www.kaggle.com/crawford/gene-expression/downloads/actual.csv'

# The local path where the data set is saved.
local_filename = "actsual.csv"

# Kaggle Username and Password
kaggle_info = 'UserName': "myUsername", 'Password': "myPassword"

# Attempts to download the CSV file. Gets rejected because we are not logged in.
r = requests.get(data_url)

# Login to Kaggle and retrieve the data.
r = requests.post(r.url, data = kaggle_info)

# Writes the data to a local file one chunk at a time.
f = open(local_filename, 'wb')
for chunk in r.iter_content(chunk_size = 512 * 1024): # Reads 512KB at a time into memory

    if chunk: # filter out keep-alive new chunks
        f.write(chunk)
f.close()

输出文件

<!DOCTYPE html>
<html>
<head>
    <title>Gene expression dataset (Golub et al.) | Kaggle</title>
    <meta charset="utf-8" />
    <meta name="robots" content="index, follow"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">    <meta name="theme-color" content="#008ABC" />
    <link rel="dns-prefetch" href="https://www.google-analytics.com" /><link rel="dns-prefetch" href="https://stats.g.doubleclick.net" /><link rel="dns-prefetch" href="https://js.intercomcdn.com" /><link rel="preload" href="https://az416426.vo.msecnd.net/scripts/a/ai.0.js" as=script /><link rel="dns-prefetch" href="https://kaggle2.blob.core.windows.net" />
    <link href="/content/v/d420a040e581/kaggle/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <link rel="manifest" href="/static/json/manifest.json">
    <link href="//fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic" rel='stylesheet' type='text/css'>
                    <link rel="stylesheet" type="text/css" href="/static/assets/vendor.css?v=72f4ef2ebe4f"/>
        <link rel="stylesheet" type="text/css" href="/static/assets/app.css?v=d997fa977b65"/>
        <script>

            (function () 
                var originalError = window.onerror;

                window.onerror = function (message, url, lineNumber, columnNumber, error) 
                    var handled = originalError && originalError(message, url, lineNumber, columnNumber, error);
                    var blockedByCors = message && message.toLowerCase().indexOf("script error") >= 0;
                    return handled || blockedByCors;
                ;
            )();
        </script>
    <script>
        var appInsights=window.appInsights||function(config)
        function i(config)t[config]=function()var i=arguments;t.queue.push(function()t[config].apply(t,i))var t=config:config,u=document,e=window,o="script",s="AuthenticatedUserContext",h="start",c="stop",l="Track",a=l+"Event",v=l+"Page",y=u.createElement(o),r,f;y.src=config.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js";u.getElementsByTagName(o)[0].parentNode.appendChild(y);tryt.cookie=u.cookiecatch(p)for(t.queue=[],t.version="1.0",r=["Event","Exception","Metric","PageView","Trace","Dependency"];r.length;)i("track"+r.pop());return i("set"+s),i("clear"+s),i(h+a),i(c+a),i(h+v),i(c+v),i("flush"),config.disableExceptionTracking||(r="onerror",i("_"+r),f=e[r],e[r]=function(config,i,u,e,o)var s=f&&f(config,i,u,e,o);return s!==!0&&t["_"+r](config,i,u,e,o),s),t
        (
            instrumentationKey:"5b3d6014-f021-4304-8366-3cf961d5b90f",
            disableAjaxTracking: true
        );
        window.appInsights=appInsights;
        appInsights.trackPageView();
    </script>

【问题讨论】:

未损坏,可能已压缩。 @OP 如果回答有帮助,请考虑Accept it as correct answer @johnson 你解决了这个问题吗?? 这里是答案***.com/a/50876207/898057 【参考方案1】:

基本上,如果你想使用 Kaggle python API(@minh-triet 提供的解决方案是针对命令行 not for python)你必须这样做以下:

import kaggle

kaggle.api.authenticate()

kaggle.api.dataset_download_files('The_name_of_the_dataset', path='the_path_you_want_to_download_the_files_to', unzip=True)

我希望这会有所帮助。

【讨论】:

我得到 ApiException: (404) 原因:未找到。我要下载的数据集称为costa-rican-household-poverty-prediction @Giacomo,找到任何方法来解决这个问题?,我得到同样的错误...... @Giacomo 您需要将用户名添加到数据集名称中。 c/哥斯达黎加家庭贫困预测 @PierreDelecto 您能否针对该问题单独回答或编辑此回答?【参考方案2】:

kaggle api 密钥和用户名在 kaggle 个人资料页面和数据集上可用 下载链接可在 kaggle 的数据集详细信息页面上获得

#Set the enviroment variables
import os
os.environ['KAGGLE_USERNAME'] = "xxxx"
os.environ['KAGGLE_KEY'] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
!kaggle competitions download -c dogs-vs-cats-redux-kernels-edition

【讨论】:

这个下载路径是什么?因为在执行您的建议后,我没有收到错误,但代码块一直在运行,我没有看到在我运行代码的文件夹中下载任何数据集。 如何不使用“!”而不是纯python?【参考方案3】:

我建议您查看Kaggle API,而不是使用您自己的代码。根据最新版本,下载数据集的示例命令是 kaggle datasets download -d zillow/zecon

【讨论】:

【参考方案4】:

完整版的示例 Download_Kaggle_Dataset_To_Colab 以及 Windows 下开始为我工作的解释

#Step1
#Input:
from google.colab import files
files.upload()  #this will prompt you to upload the kaggle.json. Download from Kaggle>Kaggle API-file.json. Save to PC to PC folder and choose it here

#Output Sample:
#kaggle.json
#kaggle.json(application/json) - 69 bytes, last modified: 29.06.2021 - 100% done
#Saving kaggle.json to kaggle.json
#'kaggle.json': 
#b'"username":"sergeysukhov7","key":"23d4d4abdf3bee8ba88e653cec******"'

#Step2
#Input:
!pip install -q kaggle
!mkdir -p ~/.kaggle
!cp kaggle.json ~/.kaggle/
!ls ~/.kaggle
!chmod 600 /root/.kaggle/kaggle.json  # set permission

#Output:
#kaggle.json

#Step3
#Input:
#Set the enviroment variables
import os
os.environ['KAGGLE_USERNAME'] = "sergeysukhov7"  #manually input My_Kaggle User_Name 
os.environ['KAGGLE_KEY'] = "23d4d4abdf3bee8ba88e653cec5*****"  #manually input My_Kaggle Key 

#Step4
#!kaggle datasets download -d zillow/zecon #download dataset to default folder content/zecon.zip if I want 

#find kaggle dataset link (for example) https://www.kaggle.com/willkoehrsen/home-credit-default-risk-feature-tools and choose part_of_the_link - willkoehrsen/home-credit-default-risk-feature-tools
#set link_from Kaggle willkoehrsen/home-credit-default-risk-feature-tools
#set Colab folder download_to  /content/gdrive/My Drive/kaggle/credit/home-credit-default-risk-feature-tools.zip
!kaggle datasets download -d willkoehrsen/home-credit-default-risk-feature-tools -p /content/gdrive/My\ Drive/kaggle/credit 

#Output
#Downloading home-credit-default-risk-feature-tools.zip to /content/gdrive/My Drive/kaggle/credit
#100% 3.63G/3.63G [01:31<00:00, 27.6MB/s]
#100% 3.63G/3.63G [01:31<00:00, 42.7MB/s]

【讨论】:

【参考方案5】:

在任何事情之前:

pip install kaggle

对于数据集:

import os
os.environ['KAGGLE_USERNAME'] = "uname" # username from the json file
os.environ['KAGGLE_KEY'] = "kaggle_key" # key from the json file
!kaggle datasets download -d zynicide/wine-reviews

对于比赛:

import os
os.environ['KAGGLE_USERNAME'] = "uname" # username from the json file
os.environ['KAGGLE_KEY'] = "kaggle_key" # key from the json file
!kaggle competitions download -c dogs-vs-cats-redux-kernels-edition

前段时间我提供了另一个similar answer。

【讨论】:

【参考方案6】:

为了方便下一个人,我将 fantastic answer from CaitLAN Jenner 与一小段代码结合起来,将原始 csv 信息放入 Pandas DataFrame,假设 row 0 具有列名。我用它从 Kaggle 下载了 Pima Diabetes 数据集,它运行良好。

我确信有更优雅的方法可以做到这一点,但它对于我正在教授的课程来说已经足够好,易于解释,并且让您可以轻松进行分析。

import pandas as pd
import requests
import csv

payload = 
    '__RequestVerificationToken': '',
    'username': 'username',
    'password': 'password',
    'rememberme': 'false'


loginURL = 'https://www.kaggle.com/account/login'
dataURL = "https://www.kaggle.com/uciml/pima-indians-diabetes-database/downloads/diabetes.csv"

with requests.Session() as c:
    response = c.get(loginURL).text
    AFToken = response[response.index('antiForgeryToken')+19:response.index('isAnonymous: ')-12]
    #print("AntiForgeryToken=".format(AFToken))
    payload['__RequestVerificationToken']=AFToken
    c.post(loginURL + "?isModal=true&returnUrl=/", data=payload)
    download = c.get(dataURL)
    decoded_content = download.content.decode('utf-8')
    cr = csv.reader(decoded_content.splitlines(), delimiter=',')
    my_list = list(cr)
    #for row in my_list:
    #    print(row)


df = pd.DataFrame(my_list)
header = df.iloc[0]
df = df[1:]
diab = df.set_axis(header, axis='columns', inplace=False)

# to make sure it worked, uncomment this next line:
# diab

`

【讨论】:

KAGGLE 发布的 API 现在是唯一的下载方式。每个用户都必须有自己的 kaggle.json 和 API 才能下载。 你可以使用我描述的方法而不使用 Kaggle API,只要你有一个有效的用户名和密码。但是,是的,Kaggle API 也可以。 @BeauHilton,我尝试了上述步骤,在我的情况下,它在某种程度上有效,我得到了 AFToken,但后来仍然返回 html 响应,不知道为什么会这样,请你帮忙关于这个?【参考方案7】:

参考https://github.com/Kaggle/kaggle-api

步骤_1, 试试 Insatling Kaggle

pip install kaggle # Windows
pip install --user kaggle # **Mac/Linux**.

第 2 步,

更新您的凭据,以便 kaggle 可以根据您从 Kaggle 生成的令牌在 .kaggle/kaggel_json 上进行身份验证。 参考:https://medium.com/@ankushchoubey/how-to-download-dataset-from-kaggle-7f700d7f9198

第 3 步 现在转为kaggle competitions download ..

运行~/.local/bin/kaggle competitions download .. 避免 Command Kaggle Not Found

【讨论】:

以上是关于使用 Python 下载 Kaggle 数据集的主要内容,如果未能解决你的问题,请参考以下文章

Kaggle数据集下载

将数据集直接从 Kaggle 下载到 GoogleColab

利用CNN进行图像分类的流程(猫狗大战为例)

如何从 Kaggle 将一个太大的 Kaggle 数据集的选定文件加载到 Colab 中

* python中Kaggle API *的文档?

kaggle有沉降数据么