简介:本文将介绍如何使用Python自动搜索图片并抓取图片。我们将使用Python的搜索引擎库,如Google Image Search API和Bing Image Search API,以及Python的图片下载库,如requests和beautifulsoup4。
在Python中,我们可以使用搜索引擎库来搜索图片,然后使用图片下载库来抓取这些图片。下面是一些可用于搜索和下载图片的库:
然后,你可以使用以下代码来搜索并下载图片:
pip install requests
在这个示例代码中,我们首先构造了一个Google Image Search API的请求URL,然后使用requests库发送GET请求获取网页内容。接下来,我们使用BeautifulSoup库解析网页内容,找到所有图片的URL,并将它们存储在image_urls列表中。最后,我们使用for循环遍历image_urls列表,下载每个图片并将其保存到本地文件夹中。注意,我们在下载每个图片时使用了with open语句打开文件并使用二进制模式写入数据。
import requestsfrom bs4 import BeautifulSoupdef search_and_download_images(keyword, num_results=10):# 构造Google Image Search API的请求URLurl = 'https://www.google.com/search?q=' + keyword + '&num=' + str(num_results) + '&tbm=isch'# 发送GET请求获取网页内容response = requests.get(url)# 使用BeautifulSoup解析网页内容soup = BeautifulSoup(response.text, 'html.parser')# 找到所有图片的URLimage_urls = []for result in soup.find_all('div', {'class': 'yuRUbf'}):img = result.find('img')if img is not None:image_urls.append(img['src'])# 下载图片并保存到本地文件夹中for i, image_url in enumerate(image_urls):filename = keyword + '_' + str(i) + '.jpg'response = requests.get(image_url, stream=True)with open(filename, 'wb') as f:for chunk in response.iter_content(chunk_size=1024):if chunk: # 检查是否有数据可读f.write(chunk)print('Images downloaded successfully!')