将图像从Subreddit保存到文件夹python

问题描述 投票:1回答:1

我一直在阅读有关Praw,bs4的大量文档,我已经看过其他人如何做到这一点的例子,但我无法按照我想要的方式获得任何工作。我认为这将是一个非常简单的脚本,但我找到的每个例子都是用python2编写的,或者根本不工作。

我想要一个脚本从给定的Subreddit下载前10个图像并将它们保存到文件夹中。

如果有人能指出我的写作方向会很棒。干杯

python-3.x reddit praw save-image
1个回答
0
投票

高级流程看起来像这样 -

  1. 迭代你的subreddit的顶部帖子。
  2. 提取提交的网址。
  3. 检查网址是否为图片。
  4. 将图像保存到所需的文件夹。
  5. 一旦有10张图像就停止。

这是一个如何实现这一点的例子 -

import urllib.request

subreddit = reddit.subreddit("aww")
count = 0

# Iterate through top submissions
for submission in subreddit.top(limit=None):

    # Get the link of the submission
    url = str(submission.url)

    # Check if the link is an image
    if url.endswith("jpg") or url.endswith("jpeg") or url.endswith("png"):

        # Retrieve the image and save it in current folder
        urllib.request.urlretrieve(url, f"image{count}")
        count += 1

        # Stop once you have 10 images
        if count == 10:
            break
© www.soinside.com 2019 - 2024. All rights reserved.