Skip to content

Update instagram_pic.py #10957

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Oct 29, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 31 additions & 10 deletions web_programming/instagram_pic.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,37 @@
from datetime import datetime

import requests
from bs4 import BeautifulSoup


def download_image(url):
try:
response = requests.get(url)
response.raise_for_status() # Check for HTTP errors

soup = BeautifulSoup(response.text, "html.parser")
image_meta_tag = soup.find("meta", {"property": "og:image"})

if image_meta_tag:
image_url = image_meta_tag.get("content")
if image_url:
image_data = requests.get(image_url).content

if image_data:
file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg"
with open(file_name, "wb") as file:
file.write(image_data)
print(f"Image downloaded and saved as {file_name}")
else:
print("Failed to download the image.")
else:
print("Image URL not found in the meta tag.")
else:
print("No meta tag with 'og:image' property found.")
except requests.exceptions.RequestException as e:
print(f"An error occurred during the HTTP request: {e}")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CONTRIBUTING.md: Algorithmic functions should not print().



if __name__ == "__main__":
url = input("Enter image url: ").strip()
url = input("Enter image URL: ").strip()
print(f"Downloading image from {url} ...")
soup = BeautifulSoup(requests.get(url).content, "html.parser")
# The image URL is in the content field of the first meta tag with property og:image
image_url = soup.find("meta", {"property": "og:image"})["content"]
image_data = requests.get(image_url).content
file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg"
with open(file_name, "wb") as fp:
fp.write(image_data)
print(f"Done. Image saved to disk as {file_name}.")
download_image(url)