首页 > 解决方案 > 使用 Praw 刮掉 subreddit 帖子标题并将它们用作文件名

问题描述

我的代码目前从给定的 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()

标签: pythonpython-3.xredditpraw

解决方案


是的,所以如果你的 'url' 变量给你一个正确的 url,那么简单的 submit.title 应该给你标题。你可能会被编码绊倒,所以你可能想用 str() 来转换它,或者用编码函数稍微花点心思。此外,许多文件名中不允许使用某些字符,因此不妨尝试从标题中删除不允许的字符。


推荐阅读