forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstagram_pic.py
More file actions
Latest commit
47 lines (36 loc) · 1.56 KB
/
Copy pathinstagram_pic.py
File metadata and controls
47 lines (36 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
fromdatetimeimportUTC, datetime
importrequests
frombs4importBeautifulSoup
defdownload_image(url: str) ->str:
"""
Download an image from a given URL by scraping the 'og:image' meta tag.
Parameters:
url: The URL to scrape.
Returns:
A message indicating the result of the operation.
"""
try:
response=requests.get(url, timeout=10)
response.raise_for_status()
exceptrequests.exceptions.RequestExceptionase:
returnf"An error occurred during the HTTP request to {url}: {e!r}"
soup=BeautifulSoup(response.text, "html.parser")
image_meta_tag=soup.find("meta", {"property": "og:image"})
ifnotimage_meta_tag:
return"No meta tag with property 'og:image' was found."
image_url=image_meta_tag.get("content")
ifnotimage_url:
returnf"Image URL not found in meta tag {image_meta_tag}."
try:
image_data=requests.get(image_url, timeout=10).content
exceptrequests.exceptions.RequestExceptionase:
returnf"An error occurred during the HTTP request to {image_url}: {e!r}"
ifnotimage_data:
returnf"Failed to download the image from {image_url}."
file_name=f"{datetime.now(tz=UTC).astimezone():%Y-%m-%d_%H:%M:%S}.jpg"
withopen(file_name, "wb") asout_file:
out_file.write(image_data)
returnf"Image downloaded and saved in the file {file_name}"
if__name__=="__main__":
url=input("Enter image URL: ").strip() or"https://www.instagram.com"
print(f"download_image({url}): {download_image(url)}")