wget:如何同时指定--directory-prefix和--output-document

8 投票
3 回答
15439 浏览
提问于 2025-04-17 10:57

当我单独使用 -P-Owget 时,一切都正常。

$: wget -P "test" http://www.google.com/intl/en_com/images/srpr/logo3w.png
Saving to: `test/logo3w.png'  

.

$: wget -O "google.png" http://www.google.com/intl/en_com/images/srpr/logo3w.png
2012-01-23 21:47:33 (1.20 MB/s) - `google.png' saved [7007/7007]

但是,把这两个选项一起用时,wget 就会忽略 -P

$: wget -P "test" -O "google.png" http://www.google.com/intl/en_com/images/srpr/logo3w.png
2012-01-23 21:47:51 (5.87 MB/s) - `google.png' saved [7007/7007]

我为目录(由网址的最后一部分生成)和文件名(通过一个计数循环生成)设置了变量,比如说 http://www.google.com/aaa/bbb/ccc 生成的 file/directory/filename,对于第一个项目来说,就是 /ccc/000.jpg

当我把这个放进代码里时:
Popen(['wget', '-O', file, theImg], stdout=PIPE, stderr=STDOUT)
wget 在每次循环中都默默失败了。

当我开启调试 -d 和日志记录 -a log.log 时,每次循环都会打印出
DEBUG output created by Wget 1.13.4 on darwin10.8.0.

当我去掉 -Ofile 时,操作就正常进行。

我的问题是:有没有办法
A) 在 wget 中同时指定 -P-O(这是我更希望的)或者
B) 在 -O 中插入一个包含 / 字符的字符串,而不会导致失败?

任何帮助都将不胜感激。

3 个回答

2

这行代码来自@Jaydev,效果非常好:

wget.download(url, path_to_output_file)

7

wget.download(..) 的文档:

def download(url, out=None, bar=bar_adaptive):
    """High level function, which downloads URL into tmp file in current
    directory and then renames it to filename autodetected from either URL
    or HTTP headers.

    :param bar: function to track download progress (visualize etc.)
    :param out: output filename or directory
    :return:    filename where URL is downloaded to
    """
    ...

使用以下方式可以将文件下载到一个已经存在的特定目录,并且可以自定义文件名:

wget.download(url, path_to_output_file)

如果你想要一个函数来自动处理目录的创建(如果目录不存在的话),那么可以使用:

urllib.urlretrieve(url, path_to_output_file)
1

你只需要把 dir/000.jpg 传给 wget-O 参数就可以了:

import subprocess
import os.path

subprocess.Popen(['wget', '-O', os.path.join(directory, filename), theImg])

从你的问题来看,不太清楚你是否已经在做类似的事情,但如果你确实这样做了还是失败了,我想到可能有两个原因:

  • 你给 -O 的参数前面有一个 /,这会导致 wget 失败,因为它没有权限在 /(根目录)下随便创建文件夹。

  • 你告诉 wget 要写入的目录不存在。你可以先用 Python 标准库里的 os.mkdir 来创建这个目录,确保它存在。

你也可以尝试去掉 Popen 调用中的 stdout=stderr= 参数,这样你就能直接看到错误信息,或者用 Python 打印出来。

撰写回答