如何使用谷歌自定义搜索api下载图像?

How to download the images using google custom search api?

提问人:merkle 提问时间:6/3/2023 最后编辑:merkle 更新时间:6/23/2023 访问量:211

问:

我在 python 中使用了 google image api 下载了 500 张图像。下载几张图片后,出现错误请求错误。下面是代码

from google_images_search import GoogleImagesSearch
import os
from tqdm import tqdm
import time


# Set up Google Images Search
gis = GoogleImagesSearch(API_KEY, API_SECRET, validate_images=False)

def download_images_in_batches(location, output_folder):
    search_params = {
        'q': location,
        'num': 50,  # Number of images to download per batch
        'fileType': 'jpg|png' # File types to include in the search
    }

    # Create the folder for the location if it doesn't exist
    location_folder = os.path.join(output_folder, location)
    os.makedirs(location_folder, exist_ok=True)

    # Download images in batches
    total_images = 500  # Total number of images to download
    images_per_batch = 50  # Number of images to download per batch
    batches = total_images // images_per_batch

    for batch in tqdm(range(batches)):
        start_index = batch * images_per_batch + 1
        search_params['start'] = start_index
        search_params['num'] = 50
        time.sleep(1)
        # Perform the search and download the images
        gis.search(search_params=search_params)

        for index, image in enumerate(gis.results()):
            if index >= images_per_batch:
                break
            image.download(location_folder)

        gis.next_page()

    print(f"Downloaded {total_images} images for {location} in folder '{location_folder}'")

download_images_in_batches('query_to_search', 'destination_path')

我想为相应的位置下载 500 张图像,我正在分批进行。下载 200 张图像后,出现以下错误

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://customsearch.googleapis.com/customsearch/v1?cx=822fca83c44f645bb&q=US+Embassy+Baghdad&searchType=image&num=10&start=201&fileType=jpg%7Cpng&safe=off&key=AIzaSyD0pMnbiJmUnFactRxZvChEqY0i2G7gkFs&alt=json returned "Request contains an invalid argument.". Details: "[{'message': 'Request contains an invalid argument.', 'domain': 'global', 'reason': 'badRequest'}]">

我的 api 限制为每天超过 500 个请求。谁能告诉我我哪里做错了?

python-3.x api python 客户端 自定义 谷歌图片搜索

评论


答: 暂无答案