【问题标题】:Save images from Subreddit to folder python将图像从 Subreddit 保存到文件夹 python
【发布时间】:2019-09-03 11:09:17
【问题描述】:

我一直在阅读有关 Praw、bs4 的大量文档,并且查看了其他人的示例,说明如何做到这一点,但我无法按照我想要的方式工作。我认为这将是一个非常简单的脚本,但我发现的每个示例要么是用 python2 编写的,要么根本不起作用。

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

如果有人能指出我的写作方向,那就太好了。 干杯

【问题讨论】:

    标签: python-3.x reddit praw save-image


    【解决方案1】:

    高级流程看起来像这样 -

    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
    

    【讨论】:

    • 您好,感谢您的回复,我已经尝试过您的代码,但它给了我错误:Traceback(最近一次通话最后一次):文件“E:/Users/Oli Shingfield/Documents/Projects// test4.py",第 7 行,在 中提交 subreddit.top(limit=None): AttributeError: 'str' object has no attribute 'top' --------------有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多