用于从 Kaggle 登录和下载的 c# 脚本

c# Script to login and download from Kaggle

最近,我遇到了一个 python 直接从 Kaggle 下载文件的脚本:https://ramhiser.com/2012/11/23/how-to-download-kaggle-data-with-python-and-requests-dot-py/

我正在尝试使用 C# 中的 WebClient 执行类似的操作。我在 Whosebug 中收到以下响应:C# download file from the web with login

尝试过使用它,但我似乎只下载了登录页面而不是实际文件。这是我的主要代码:

CookieContainer cookieJar = new CookieContainer();
CookieAwareWebClient http = new CookieAwareWebClient(cookieJar);

string postData = "name=<username>&password=<password>&submit=submit";
string response = http.UploadString("https://www.kaggle.com/account/login", postData);
Console.Write(response);

http.DownloadFile("https://www.kaggle.com/c/titanic/download/train.csv", "train.CSV");

我使用了上面 link 的 Webclient 扩展并稍作修改:

public class CookieAwareWebClient : WebClient
{
    public CookieContainer CookieContainer { get; set; }
    public Uri Uri { get; set; }

    public CookieAwareWebClient()
        : this(new CookieContainer())
    {
    }

    public CookieAwareWebClient(CookieContainer cookies)
    {
        this.CookieContainer = cookies;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        this.Uri = address;
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = this.CookieContainer;
        }
        HttpWebRequest httpRequest = (HttpWebRequest)request;
        httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        return httpRequest;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse r = base.GetWebResponse(request);
        var response = r as HttpWebResponse;
        if (response != null)
        {
            CookieCollection cookies = response.Cookies;
            CookieContainer.Add(cookies);
        }
        return response;
    }
}

想知道是否有人可以指出我哪里出错了?

谢谢。

尝试在未登录的情况下通过浏览器转到 https://www.kaggle.com/c/titanic/download/train.csv,您的浏览器将打开该页面而不是下载您的文件。您需要直接 link 到文件而不是网页。

您的代码运行完美,您只需要直接 link 到该文件或确保您在下载文件之前已登录。

我知道这不完全是您要问的,但是 Kaggle now has an official API 您可以用来下载数据。应该更容易使用。 :)

我们创建了一个论坛 post 来帮助您完成您想做的事情,Accessing Kaggle API through C#。如果您有其他问题,请随时 post 此处或论坛。