【发布时间】:2015-05-17 08:52:21
【问题描述】:
代码说明
我下面的脚本工作正常。它基本上只是从给定的网站上找到我感兴趣的所有数据文件,检查它们是否已经在我的计算机上(如果存在则跳过它们),最后使用 cURL 将它们下载到我的计算机上。
问题
我遇到的问题是有时有 400 多个非常大的文件,我无法同时下载它们。我会按 Ctrl-C 但它似乎取消了 cURL 下载而不是脚本,所以我最终需要一一取消所有下载。有没有解决的办法?也许以某种方式制作一个让我在当前下载结束时停止的关键命令?
#!/usr/bin/python
import os
import urllib2
import re
import timeit
filenames = []
savedir = "/Users/someguy/Documents/Research/VLF_Hissler/Data/"
#connect to a URL
website = urllib2.urlopen("http://somewebsite")
#read html code
html = website.read()
#use re.findall to get all the data files
filenames = re.findall('SP.*?\.mat', html)
#The following chunk of code checks to see if the files are already downloaded and deletes them from the download queue if they are.
count = 0
countpass = 0
for files in os.listdir(savedir):
if files.endswith(".mat"):
try:
filenames.remove(files)
count += 1
except ValueError:
countpass += 1
print "counted number of removes", count
print "counted number of failed removes", countpass
print "number files less removed:", len(filenames)
#saves the file names into an array of html link
links=len(filenames)*[0]
for j in range(len(filenames)):
links[j] = 'http://somewebsite.edu/public_web_junk/southpole/2014/'+filenames[j]
for i in range(len(links)):
os.system("curl -o "+ filenames[i] + " " + str(links[i]))
print "links downloaded:",len(links)
【问题讨论】:
-
将内容读入 var 并将内容写入文件。在这种情况下,您不必使用 curl。此外,要解析 HTML,您不应使用正则表达式。另一个提示,使用线程同时进行下载。
-
哦,这是个好主意,而且有点明显的写入文件会很好。我不确定如何下载没有 cURL 的文件?为什么正则表达式不适合解析 html?我也会研究线程。
-
您将打开网址
links[j] = 'http://somewebsite.edu/public_web_junk/southpole/2014/'+filenames[j],读取其内容data = str(urlConn.readlines()),然后打开一个文件以写入f = open(filenames[j], 'w') f.write(data)
标签: python loops curl terminate