如何使用媒体网址将 Instagram 故事保存在我的媒体文件夹中?

问题描述

def save_media(story_id,media_url):
try:
    link = media_url[:media_url.find('?')]
    extension = link[::-1][:link[::-1].find('.')+1][::-1]
    if 'video' in media_url:
        extension = '.mp4'
        
    filepath = r'{0}\file path for media to save stories\{1}{2}'.format(os.getcwd(),story_id,extension)
    if not os.path.exists(filepath):
        response = requests.get(media_url)
        if response.status_code==200:
            with open(r'{}'.format(filepath),'wb') as file:
                file.write(response.content)
            file.close()
    newpath = filepath.replace(f'{os.getcwd()}\\influnite','')
    return newpath
except Exception as error:
    print('Error saving story media!')
    print(error)
    return ''

运行此代码后从 api 获取媒体 url 我没有在媒体文件夹中获取媒体数据(视频和故事) 有人可以告诉我我在做什么错误吗?

解决方法

def save_media(story_id,media_url):
try:
    link = media_url[:media_url.find('?')]
    extension = link[::-1][:link[::-1].find('.')+1][::-1]
    if 'video' in media_url:
        extension = '.mp4'
        
    filepath = r'{0}/influnite/media/stories/{1}{2}'.format(os.getcwd(),story_id,extension)
    if not os.path.exists(filepath):
        response = requests.get(media_url)
        if response.status_code==200:
            with open(filepath,'wb') as file:
                file.write(response.content)
            file.close()
    newpath = filepath.replace(r'{0}/influnite'.format(os.getcwd()),'')
    return newpath
except Exception as error:
    print('Error saving story media!')
    print(error)
    return ''

这里首先检查获取的故事是jpg格式或mp4格式,然后检查来自服务器的响应并将故事和文件保存为wb,即以位写入并将故事保存在 media 文件夹

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...