python - Python Reddit API 将 gifv 转换为可读的 mp4
问题描述
当涉足 Reddit 的 API aka Praw 时,我完全陷入困境,我想学习将排名第一的最热门帖子保存为 mp4,但是 Reddit 将他们所有的 gif 保存在 Imgur 上,将所有 gif 转换为 gifv,我将如何转换 gifv到 mp4 以便我可以阅读它们?顺便说一句,简单地重命名它似乎会导致腐败。到目前为止,这是我的代码:(为保密起见,详细信息已 xxxx)
reddit = praw.Reddit(client_id ="xxxx" , client_secret ="xxxx", username = "xxxx", password ="xxxx", user_agent="xxxx")
subreddit = reddit.subreddit("dankmemes")
hot_dm = subreddit.hot(limit=1);
for sub in hot_dm:
print(sub)
url = sub.url
print(url)
print(sub.permalink)
meme = requests.get(url)
newF = open("{}.mp4".format(sub), "wb") #here the file is created but when played is corrupted
newF.write(meme.content)
newF.close()
解决方案
一些帖子已经在 json 响应的预览 > 变体部分中进行了 mp4 转换。
因此,要仅下载那些具有 gif 并因此具有 mp4 版本的帖子,您可以执行以下操作:
subreddit = reddit.subreddit("dankmemes")
hot_dm = subreddit.hot(limit=10)
for sub in hot_dm:
if sub.selftext == "": # check that the post is a link to some content (image/video/link)
continue
try: # try to access variants and catch the exception thrown
has_variants = sub.preview['images'][0]['variants'] # variants contain both gif and mp4 versions (if available)
except AttributeError:
continue # no conversion available as variants doesn't exist
if 'mp4' not in has_variants: # check that there is an mp4 conversion available
continue
mp4_video = has_variants['mp4']['source']['url']
print(sub, sub.url, sub.permalink)
meme = requests.get(mp4_video)
with open(f"{sub}.mp4", "wb") as newF:
newF.write(meme.content)
尽管您很可能希望在搜索热门帖子时增加查看帖子的限制,因为第一个帖子可能是固定帖子(通常是关于 subreddit 的一些规则),但这就是我最初检查自文的原因。此外,可能还有其他只有图像的帖子,因此在很小的限制下,您可能不会返回任何可以转换为 mp4 的帖子。
推荐阅读
- javascript - Javascript:如何调用数组数组中的不同对象?
- android - android.support.constraint.ConstraintLayout 不能转换为 android.widget.EditText
- javascript - 在背景音乐中添加两秒延迟
- r - 在R中将aplucter的结果绑定到数据帧
- java - 以编程方式确定 Java 类是否被修补?
- php - 如何更改 Crinsane/LaravelShoppingcart 中的默认货币?
- c# - 我收到一个错误。“Where”和“Take”值未出现在列表数据中
- c# - 使用测试工具,需要编写一个函数,使测试用例通过 IndexOf 一个字符串和一个字符
- bdd - 如果前面的步骤在 Jbehave 中失败,如何停止执行后面的步骤
- c# - Unity 访问对撞机作为不同游戏对象上的公共变量