python - 使用 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()
解决方案
是的,所以如果你的 'url' 变量给你一个正确的 url,那么简单的 submit.title 应该给你标题。你可能会被编码绊倒,所以你可能想用 str() 来转换它,或者用编码函数稍微花点心思。此外,许多文件名中不允许使用某些字符,因此不妨尝试从标题中删除不允许的字符。
推荐阅读
- javascript - 将 ACF 与 GraphQL 和 Gatsby 一起使用,灵活的内容不会返回其子块的顺序
- html - Bootstrap Carousel li 项目活动类不工作
- c# - 在 Sql 查询中使用参数
- macos - 由于“二进制文件使用的 SDK 早于 10.9 SDK”,电子公证失败。
- php - 避免 3 个 Wordpress 循环中的重复帖子
- javascript - 如何检查 JS 中是否存在(根本)变量?
- python - Yaml 转储程序从 None 值输出空白而不是 null。如何让它输出 null 呢?
- elasticsearch - Send custom build info from Jenkins to Elasticsearch
- android - 减少 ListView 中滚动条的淡入淡出动画时间
- python - 为什么这两个 ODE 求解程序不匹配?