如果未下载则从列表中下载文件
我可以用C#来做到这一点,不过代码挺长的。
如果有人能告诉我用Python怎么做,那就太好了。
伪代码是:
url: www.example.com/somefolder/filename1.pdf
1. load file into an array (file contains a url on each line)
2. if file e.g. filename1.pdf doesn't exist, download file
这个脚本可以按照以下结构来写:
/python-downloader/
/python-downloader/dl.py
/python-downloader/urls.txt
/python-downloader/downloaded/filename1.pdf
3 个回答
2
在Python中代码更少,你可以用这样的方式:
import urllib2
improt os
url="http://.../"
# Translate url into a filename
filename = url.split('/')[-1]
if not os.path.exists(filename)
outfile = open(filename, "w")
outfile.write(urllib2.urlopen(url).read())
outfile.close()
14
这是一个稍微修改过的WoLpH的脚本,适用于Python 3.3。
#!/usr/bin/python3.3
import os.path
import urllib.request
links = open('links.txt', 'r')
for link in links:
link = link.strip()
name = link.rsplit('/', 1)[-1]
filename = os.path.join('downloads', name)
if not os.path.isfile(filename):
print('Downloading: ' + filename)
try:
urllib.request.urlretrieve(link, filename)
except Exception as inst:
print(inst)
print(' Encountered unknown error. Continuing.')
23
这样做应该可以解决问题,不过我假设 urls.txt
文件里只包含网址,不包括 url:
这个前缀。
import os
import urllib
DOWNLOADS_DIR = '/python-downloader/downloaded'
# For every line in the file
for url in open('urls.txt'):
# Split on the rightmost / and take everything on the right side of that
name = url.rsplit('/', 1)[-1]
# Combine the name and the downloads directory to get the local filename
filename = os.path.join(DOWNLOADS_DIR, name)
# Download the file if it does not exist
if not os.path.isfile(filename):
urllib.urlretrieve(url, filename)