Created
August 28, 2023 07:14
-
-
Save halovivek/895c46929ae53806628e94231070f734 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import requests | |
from bs4 import BeautifulSoup | |
from urllib.parse import urljoin | |
def download_images_from_webpage(url, save_folder): | |
response = requests.get(url) | |
if response.status_code == 200: | |
soup = BeautifulSoup(response.text, 'html.parser') | |
img_tags = soup.find_all('img') | |
for img_tag in img_tags: | |
img_url = img_tag.get('src') | |
if img_url: | |
img_url = urljoin(url, img_url) | |
response = requests.get(img_url) | |
if response.status_code == 200: | |
img_name = os.path.basename(img_url) | |
img_path = os.path.join(save_folder, img_name) | |
with open(img_path, 'wb') as img_file: | |
img_file.write(response.content) | |
print(f"Image '{img_name}' downloaded and saved as '{img_path}'.") | |
else: | |
print(f"Failed to retrieve image '{img_url}'. Status code:", response.status_code) | |
else: | |
print("Failed to retrieve the URL. Status code:", response.status_code) | |
if __name__ == "__main__": | |
webpage_url = "https://www.wallpaperflare.com/search?wallpaper=space" # Replace with the webpage URL you want to scrape | |
save_directory = "downloaded_images" # Specify the directory to save the images | |
if not os.path.exists(save_directory): | |
os.makedirs(save_directory) | |
download_images_from_webpage(webpage_url, save_directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment