刮除subreddit帖子标题,并使用Praw将它们用作文件名

时间:2019-04-18 13:53:33

标签: python python-3.x reddit praw

我的代码当前从给定的subreddit下载图像,并将其命名为原始文件名。我希望代码能够将它们命名为它们在Reddit上发布的名称。有人可以帮我吗?我认为这与Submission.title有关,但我无法弄清楚。欢呼。

import praw
import threading
from requests import get
from multiprocessing.pool import ThreadPool
import os


client_id = 'xxxxxxxxx'
client_secret = 'xxxxxxxxx'
user_agent = 'xxxxxxxxx'
image_directory = 'images'
thread_count = 16

target_subreddit = 'space'
image_count = '10'
order = 'hot'

order = order.lower()

reddit = praw.Reddit(client_id=client_id,
                     client_secret=client_secret, user_agent=user_agent)


def get_order():
    if order == 'hot':
        ready = reddit.subreddit(target_subreddit).hot(limit=None)
    elif order == 'top':
        ready = reddit.subreddit(target_subreddit).top(limit=None)
    elif order == 'new':
        ready = reddit.subreddit(target_subreddit).new(limit=None)
    return ready


def get_img(what):
    image = '{}/{}/{}'.format(image_directory,
                              target_subreddit, what.split('/')[-1])
    img = get(what).content
    with open(image, 'wb') as f:
        f.write(img)


def make_dir():
    directory = f'{image_directory}/{target_subreddit}'
    if not os.path.exists(directory):
        os.makedirs(directory)


def main():
    c = 1
    images = []
    make_dir()
    for submission in get_order():
        url = submission.url
        if url.endswith(('.jpg', '.png', '.gif', '.jpeg')):
            images.append(url)
            c += 1
            if int(image_count) < c:
                break

    results = ThreadPool(thread_count).imap_unordered(get_img, images)
    for path in results:
        pass

    print('Done')

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

是的,因此,如果您的'url'变量为您提供了正确的url,则只需Submit.title应该为您提供标题。您可能不喜欢这种编码,所以您可能想用str()进行转换,或者有点fancier with the encode function.。此外,许多文件名中不允许使用某些字符,因此请尝试从中剥离掉不允许的字符标题。