使用post方法和python下载文件

时间:2021-01-18 09:57:04

I need a little help getting a tar file to download from a website. The website is set up as a form where you pick the file you want and click submit and then the download windows opens up for you to pick the location.

我需要一点帮助从网站上下载tar文件。该网站设置为您选择所需文件的表单,然后单击“提交”,然后打开下载窗口以供您选择位置。

I'm trying to do the same thing in code (so I don't have to manual pick each file). So far I have gotten python 2.5.2 to return a response but its in a socket._fileobject and I'm now not sure how to convert that into a file on my computer.

我试图在代码中做同样的事情(所以我不必手动选择每个文件)。到目前为止,我已经得到python 2.5.2来返回响应,但它在socket._fileobject中,我现在不知道如何将其转换为我的计算机上的文件。

Below is output of the python shell and the steps I have taken

下面是python shell的输出和我采取的步骤

Python 2.5.2 on win32

IDLE 1.2.2      
>>> import urllib
>>> import urllib2
>>> url = 'http://website/getdata.php'
>>> values = {'data[]': 'filex.tar'}
>>> data = urllib.urlencode(values)
>>> req = urllib2.Request(url,data)
>>> response = urllib2.urlopen(req)
>>> response
addinfourl at 22250280 whose fp = <socket._fileobject object at 0x01534570
>>> response.fp
socket._fileobject object at 0x01534570

1 个解决方案

#1


Append this:

myfile = open('myfile.tar', 'wb')
shutil.copyfileobj(response.fp, myfile)
myfile.close()

response.fp is a file-like object that you can read from, just like an open file. shutil.copyfileobj() is a simple function that reads from one file-like object and writes its contents to another.

response.fp是一个类似文件的对象,您可以从中读取,就像打开文件一样。 shutil.copyfileobj()是一个简单的函数,它从一个类似文件的对象读取并将其内容写入另一个。

#1


Append this:

myfile = open('myfile.tar', 'wb')
shutil.copyfileobj(response.fp, myfile)
myfile.close()

response.fp is a file-like object that you can read from, just like an open file. shutil.copyfileobj() is a simple function that reads from one file-like object and writes its contents to another.

response.fp是一个类似文件的对象,您可以从中读取,就像打开文件一样。 shutil.copyfileobj()是一个简单的函数,它从一个类似文件的对象读取并将其内容写入另一个。