使用Python下載Instagram個人資料圖片


可以使用Python中的Beautiful Soup和Requests模組下載Instagram個人資料圖片。Instagram是最受歡迎的社交媒體平臺之一,允許使用者與關注者分享照片和影片。作為Instagram使用者,您可能會遇到一些您想儲存或下載的有趣的個人資料圖片。在本文中,我們將使用Python中的Beautiful Soup和Instaloader庫下載Instagram個人資料圖片。

方法一:使用Beautiful Soup和Requests模組

在這種方法中,我們使用requests模組向用戶的Instagram個人資料URL傳送GET請求,它將返回HTML響應。我們需要解析HTML響應並提取使用者的個人資料圖片。這可以使用Beautiful Soup來完成,方法是查詢屬性屬性設定為`og:image`的meta標籤,該標籤在content屬性中包含使用者個人資料圖片的URL。

示例

在下面的示例中,`download_profile_pic('Instagram')`函式中的Instagram是您要下載個人資料圖片的使用者的使用者名稱。

import requests
from bs4 import BeautifulSoup

def download_profile_pic(username):
   # create the URL for the user's Instagram profile
   url = f"https://www.instagram.com/{username}/"

   # send a GET request to the URL and get the HTML response
   response = requests.get(url)

   # parse the HTML response using BeautifulSoup
   soup = BeautifulSoup(response.content, 'html.parser')

   # find the  tag containing the URL of the profile picture
   meta_tag = soup.find('meta', attrs={'property': 'og:image'})

   # extract the URL from the 'content' attribute of the  tag
   profile_pic_url = meta_tag['content']

   # create the filename for the downloaded profile picture
   file_name = f"{username}_profile_pic.jpg"

   # send a GET request to the profile picture URL and download the image
   pic_response = requests.get(profile_pic_url)
   with open(file_name, 'wb') as f:
      f.write(pic_response.content)

   print(f"Profile picture for {username} downloaded successfully!")

# example usage: download the profile picture of the user 'instagram'
download_profile_pic('instagram')

輸出

Profile picture for rohit_the_lucifer downloaded successfully!

方法二:使用Instaloader庫

在使用instaloader庫之前,我們需要使用Python中的pip命令安裝該庫。

pip install instaloader

現在,要使用instaloader庫下載Instagram個人資料圖片,請匯入instaloader庫,然後建立一個Instaloader類的例項,並使用instaloader類的`download_profile()`函式下載個人資料圖片。

示例

在下面的程式碼中,輸入您要下載個人資料圖片的Instagram使用者名稱。

import instaloader

# Create an instance of the Instaloader class
loader = instaloader.Instaloader()

dp = "instagram_user_name"

# Download the profile picture of the user
loader.download_profile(dp, profile_pic_only=True)

print(f"Profile picture for {dp} downloaded successfully!")

輸出

Profile picture for instagram_user_name downloaded successfully!

結論

在本文中,我們討論瞭如何使用Python中的Beautiful Soup和instaloader庫下載Instagram個人資料圖片。Beautiful Soup用於解析HTML內容並獲取個人資料圖片的URL,以便使用Python中的requests模組下載它。您可以使用此程式碼下載朋友、家人甚至您最喜歡的名人的個人資料圖片。

更新於:2023年7月10日

瀏覽量:1000+

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.