gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
import os import requests from googlesearch import search def downloadimages(keyword,…
- User
import os import requests from googlesearch import search
def download_images(keyword, limit): # Create a directory to store the downloaded images os.makedirs(keyword, exist_ok=True)
# Perform a Google search for images query = f"{keyword} images" urls = search(query, num_results=limit) # Download the images for i, url in enumerate(urls, start=1): try: response = requests.get(url) response.raise_for_status() filename = os.path.join(keyword, f"{keyword}_{i}.jpg") with open(filename, "wb") as f: f.write(response.content) print(f"Downloaded image {i}/{limit}") except Exception as e: print(f"Error downloading image {i}: {str(e)}")Example usage
download_images("cats", 10)
- Assistant
The code provided is a function that downloads images using the Google search API and the requests library. Here's how it works:
- The function takes two parameters:
keyword(the search term) andlimit(the number of images to download). - It creates a directory with the
keywordname to store the downloaded images if it doesn't already exist. - It performs a Google search for images using the
queryvariable, which combines thekeywordand the string "images". - It uses the
searchfunction from thegooglesearchlibrary to fetch a list of image URLs. - It downloads the images one by one using a
forloop. The loop assigns an indexito each image, starting from 1. - Inside the loop, it sends a GET request to the URL, raises an exception if the status code is not 200 (indicating a successful request), and saves the image to a file with the
keywordandiin the filename. - Finally, it prints a message indicating the progress of the download or any errors encountered.
- The function takes two parameters: