如何使wget python模块不下载重复项?

时间:2018-08-31 03:20:48

标签: python wget

当尝试从4chan上的帖子下载文件(通过BASC_py4chan)并通过wget下载文件时,即使我做出一条if语句说如果文件名与文件名相同也不要下载,wget也会下载文件在当前目录中?这是wget-python问题还是我做错了?

    if 'ylyl' in subject or 'YLYL' in subject:
    for post in thread.all_posts:
        if post.has_file:
            print(post.filename)
            for filename in os.listdir(cwd):
                print(filename)
                if filename != post.filename:
                    url = post.file_url
                    wget.download(url)
                    time.sleep(1.03)

2 个答案:

答案 0 :(得分:0)

我认为您可以将代码更改为

if 'ylyl' in subject or 'YLYL' in subject:
    for post in thread.all_posts:
        if post.has_file:
        print(post.filename)
        # changed at here
        if post.filename not in os.listdir(cwd):
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

答案 1 :(得分:0)

我看到您的代码有问题。问题出在这一点:

    for filename in os.listdir(cwd):
        print(filename)
        if filename != post.filename:
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

您正在循环浏览目录中的每个文件。这意味着,如果目录中的文件名与帖子的文件名不同,则将下载该文件。

因此,假设您的代码正在尝试下载file3,并且目录中包含file1,file2和file3。

将这些文件放在目录中,您的if语句将进行这3次检查。

        if 'file1' != 'file3':
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

        if 'file2' != 'file3':
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

        if 'file3' != 'file3':
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

您可能想尝试的是检查文件名是否在os.listdir()返回的列表中。

这是我的解决方法:

if 'ylyl' in subject or 'YLYL' in subject:
for post in thread.all_posts:
    if post.has_file:
        print(post.filename)
        if post.filename not in os.listdir(cwd):
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)