使用が最も簡単な解決策の1つであるというBlairg23に同意します。urllib.request.urlretrieve
ここで指摘したいことが1つあります。リクエストがスクリプト(ボット)経由で送信されたために何もダウンロードされない場合があります。Google画像や他の検索エンジンからの画像を解析する場合は、最初user-agent
にリクエストに渡してからheaders
画像をダウンロードする必要があります。それ以外の場合は、リクエストはブロックされ、エラーがスローされます。
画像を渡しuser-agent
てダウンロードします。
opener=urllib.request.build_opener()
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582')]
urllib.request.install_opener(opener)
urllib.request.urlretrieve(URL, 'image_name.jpg')
requests
、、bs4
を使用してGoogle画像から画像をスクレイプしてダウンロードするオンラインIDEのコードurllib.requests
。
または、Google、Bing、Yahoo!、DuckDuckGo(およびその他の検索エンジン)などの検索エンジンから画像を取得することが目標の場合は、SerpApiを使用できます。これは無料プランの有料APIです。
最大の違いは、検索エンジンからブロックをバイパスする方法や、HTMLまたはJavaScriptから特定の部分を抽出する方法を理解する必要がないことです。これは、エンドユーザー向けにすでに行われているためです。
統合するコード例:
import os, urllib.request
from serpapi import GoogleSearch
params = {
"api_key": os.getenv("API_KEY"),
"engine": "google",
"q": "pexels cat",
"tbm": "isch"
}
search = GoogleSearch(params)
results = search.get_dict()
print(json.dumps(results['images_results'], indent=2, ensure_ascii=False))
# download images
for index, image in enumerate(results['images_results']):
# print(f'Downloading {index} image...')
opener=urllib.request.build_opener()
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582')]
urllib.request.install_opener(opener)
# saves original res image to the SerpApi_Images folder and add index to the end of file name
urllib.request.urlretrieve(image['original'], f'SerpApi_Images/original_size_img_{index}.jpg')
-----------
'''
]
# other images
{
"position": 100, # 100 image
"thumbnail": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQK62dIkDjNCvEgmGU6GGFZcpVWwX-p3FsYSg&usqp=CAU",
"source": "homewardboundnj.org",
"title": "pexels-helena-lopes-1931367 - Homeward Bound Pet Adoption Center",
"link": "https://homewardboundnj.org/upcoming-event/black-cat-appreciation-day/pexels-helena-lopes-1931367/",
"original": "https://homewardboundnj.org/wp-content/uploads/2020/07/pexels-helena-lopes-1931367.jpg",
"is_product": false
}
]
'''
免責事項、私はSerpApiで働いています。