如何使用Python下载文件?

Ale*_*lex 6 python get download

我对 Python 完全陌生,我想通过向服务器发送请求来下载文件。当我在浏览器中输入它时,我看到 CSV 文件已下载,但是当我尝试发送 get 请求时,它没有返回任何内容。例如:

import urllib2
response = urllib2.urlopen('https://publicwww.com/websites/%22google.com%22/?export=csv')
data = response.read()
print 'data: ',  data
Run Code Online (Sandbox Code Playgroud)

它没有显示任何内容,我该如何处理?当我在网上搜索时,所有的问题都是关于如何发送一个 get 请求。我可以发送 get 请求,但我不知道如何下载文件,因为它不在请求的响应中。

我不知道如何找到解决方案。

Rak*_*esh 10

您可以使用urlretrieve下载文件

前任:

u = "https://publicwww.com/websites/%22google.com%22/?export=csv"

import urllib
urllib.request.urlretrieve (u, "Ktest.csv")
Run Code Online (Sandbox Code Playgroud)


big*_*nty 8

您还可以使用 python 中的请求模块下载文件。

import shutil

import requests

url = "https://publicwww.com/websites/%22google.com%22/?export=csv"
response = requests.get(url, stream=True)
with open('file.csv', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response
Run Code Online (Sandbox Code Playgroud)


wha*_*000 2

import os
os.system("wget https://publicwww.com/websites/%22google.com%22/?export=csv")
Run Code Online (Sandbox Code Playgroud)

如果你有的话,你可以尝试一下 wget。

  • 请不要在没有提供理由的情况下投反对票,我看到有两张反对票,但没有一个理由。 (3认同)