0

我正在使用以下代码下载我的文件:

def downloadfile(url): #function to download file    
    file_name = filename_parse(url)
    #print "***********************"
    #print "File download started:"
    #stime= time.time()
    u = urllib2.urlopen(url)
    f = open(file_name, 'wb')
    getfilesize(u)
    file_size = getfilesize(u)
    print "Downloading: %s Bytes: %s \n" % (file_name, file_size)
    file_size_dl = 0
    block_sz = 512
    progressbar(u,block_sz,file_size_dl,f,file_size)
f.close()

问题是它可以下载除 .pdf 文件之外的任何文件 exe、txt 和其他文件……我怎样才能让它下载 pdf 文件?

4

1 回答 1

0

我知道这是一个老问题,但对于所有偶然发现它并想使用 python 2 和 urllib2 下载 pdf 文件的人来说,这里是代码:

import urllib2
url = 'http://mensenhandel.nl/files/pdftest2.pdf'
print "Download started..."
f = urllib2.urlopen(url)
data = f.read()
with open("test.pdf", "wb") as code:
    code.write(data)
print "Download completed..."

只需根据您的需要修改 URL...

来源: http: //www.blog.pythonlibrary.org/2012/06/07/python-101-how-to-download-a-file/

于 2015-07-11T20:20:33.457 回答