Skip to content

Instantly share code, notes, and snippets.

@Jackenmen
Created October 2, 2022 15:58
Show Gist options
  • Save Jackenmen/d44c401f2edd2c6cfd6349a04b223881 to your computer and use it in GitHub Desktop.
Save Jackenmen/d44c401f2edd2c6cfd6349a04b223881 to your computer and use it in GitHub Desktop.
Download images from the given Facebook posts
import operator
import requests
API_URL = "https://graph.facebook.com/v15.0/"
TOKEN = ""
PAGE_ID = ""
# {"post_id": "folder name"}
POST_IDS = {}
def process_photos(folder_name, resp_data):
photos = (
subattachment["target"]["id"]
for attachment in resp_data["attachments"]["data"]
for subattachment in attachment.get("subattachments", {}).get("data", [])
)
for idx, photo_id in enumerate(photos, start=1):
print("Processing photo with ID", photo_id)
resp = session.get(
f"{API_URL}{photo_id}", params={"fields": "images", "access_token": TOKEN}
)
resp.raise_for_status()
image = max(resp.json()["images"], key=operator.itemgetter("width"))
with open(f"{folder_name}/{idx}.jpg", "wb") as fp:
with session.get(image["source"], stream=True) as resp:
resp.raise_for_status()
for chunk in resp.iter_content(chunk_size=128):
fp.write(chunk)
def main() -> int:
with requests.Session() as session:
for post_id, folder_name in POST_IDS.items():
print("--- Processing post with ID", post_id)
full_post_id = f"{PAGE_ID}_{post_id}"
resp = session.get(
f"{API_URL}{full_post_id}",
params={
"fields": "attachments{subattachments.limit(100){target{id}}}",
"access_token": access_token,
},
)
resp.raise_for_status()
folder_name = folder_name or full_post_id
process_photos(full_post_id, resp.json())
return 0
if __name__ == "__main__":
raise SystemExit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment