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 8 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
74 changes: 63 additions & 11 deletions web_programming/instagram_pic.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,68 @@
from datetime import datetime

from typing import Optional
Copy link
Member

Choose a reason for hiding this comment

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

Not needed on Python 3.12

Suggested change
from typing import Optional

Copy link
Contributor Author

Choose a reason for hiding this comment

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

OK

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@cclauss tried many times but every time getting this error
Error: web_programming/instagram_pic.py:1:1: I001 Import block is un-sorted or un-formatted

Copy link
Member

Choose a reason for hiding this comment

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

If the imports were working fine before, then do not change them.

Click the text I001 to read the rule and how it works.

python3 -m pip install ruff and then ruff --select=I --fix web_programming/instagram_pic.py

import requests
from bs4 import BeautifulSoup


def validate_url(url: str) -> bool:
"""
Validates the given URL.
>>> validate_url("https://www.example.com")
True
"""
# Add URL validation logic here
return True


def download_image_data(image_url: str) -> Optional[bytes]:
"""
Downloads image data from the given URL.
>>> download_image_data("https://www.example.com/image.jpg") # This is a hypothetical example; actual output may vary.
b'...'
"""
try:
return requests.get(image_url).content
except requests.exceptions.RequestException:
return None


def save_image(image_data: bytes, file_name: str) -> None:
"""
Saves the image data to a file.
"""
with open(file_name, "wb") as file:
file.write(image_data)


def download_image(url: str) -> str:
"""
Downloads an image from the given URL and saves it to a file.
>>> download_image("https://www.example.com") # This is a hypothetical example; actual output may vary.
'Image downloaded and saved as image_2023-10-29_12:34:56.jpg'
"""
try:
response = requests.get(url)
response.raise_for_status()

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 = download_image_data(image_url)
if image_data:
file_name = f"image_{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg"
save_image(image_data, file_name)
return f"Image downloaded and saved as {file_name}"
except requests.exceptions.RequestException:
return "An error occurred during the HTTP request."


if __name__ == "__main__":
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}.")
url = input("Enter image URL: ").strip()
if validate_url(url):
result = download_image(url)
print(result)
else:
print("Invalid URL. Please try again.")