如果我运行 wget 两次,它不会识别它已经下载了该文件,并创建了一个新文件。有什么办法可以防止它再次下载文件?
$ wget https://cdn.sstatic.net/askubuntu/img/logo.png
...
Saving to: ‘logo.png’
...
$ wget https://cdn.sstatic.net/askubuntu/img/logo.png
...
Saving to: ‘logo.png.1’
...
Run Code Online (Sandbox Code Playgroud)
(如果 wget 不能这样做,很高兴使用 curl 或类似的可编写脚本的替代方案。)
小智 19
我建议您使用该-N选项。
-N
--timestamping
Turn on time-stamping.
Run Code Online (Sandbox Code Playgroud)
它启用时间戳,仅当服务器上的文件比下载的版本更新时才重新下载文件。
$ wget -N https://cdn.sstatic.net/askubuntu/img/logo.png
...
Saving to: ‘logo.png’
...
$ wget -N https://cdn.sstatic.net/askubuntu/img/logo.png
...
Server file no newer than local file ‘logo.png’ -- not retrieving.
Run Code Online (Sandbox Code Playgroud)
警告(来自 ??s??? 的评论)
如果服务器没有正确配置,它可能总是报告文件是新的,并且-N总是会重新下载文件。在这种情况下,-nc可能是更好的选择。
αғs*_*нιη 16
是的,它的-c选择。
--continue
Continue getting a partially-downloaded file. This is useful when you want to
finish up a download started by a previous instance of Wget, or by another
program.
Run Code Online (Sandbox Code Playgroud)
如果文件相同,则第二次下载尝试将停止。
$ wget -c https://cdn.sstatic.net/askubuntu/img/logo.png
...
Saving to: ‘logo.png’
...
$ wget -c https://cdn.sstatic.net/askubuntu/img/logo.png
...
The file is already fully retrieved; nothing to do.
Run Code Online (Sandbox Code Playgroud)
注意事项(来自 jofel 的评论)
如果服务器上的文件已更改,则该-c选项可能会给出不正确的结果。
使用-c,wget 只要求服务器提供已下载文件部分以外的任何数据,没有别的。它不会检查已下载的文件部分是否有任何更改。因此,您可能会损坏一个混合了旧文件和新文件的文件。
本地测试
您可以通过运行简单的本地网络服务器来测试它,如下所示(感谢@roadmr的回答):
打开终端窗口并输入:
cd /path/to/parent-download-dir/
python -m SimpleHTTPServer
Run Code Online (Sandbox Code Playgroud)
现在打开另一个终端并执行:
wget -c http://localhost:8000/filename-to-download
Run Code Online (Sandbox Code Playgroud)
请注意,这filename-to-download是/path/to/parent-download-dir/我们要下载它的文件。
现在,如果您多次运行 wget 命令,您将看到:
The file is already fully retrieved; nothing to do.
Run Code Online (Sandbox Code Playgroud)
好的,现在转到/path/to/parent-download-dir/目录并向源文件添加一些内容,例如,如果它是一个文本文件,则在其中添加一个简单的额外行并保存文件。现在尝试使用wget -c .... 太好了,现在您将再次看到文件重新下载,但您之前已经下载过。
因为它的大小变成了比旧的下载文件更大的大小,没有别的。