Python自动搜索图片并抓取图片

作者:carzy2024.01.08 12:25浏览量:9

简介:本文将介绍如何使用Python自动搜索图片并抓取图片。我们将使用Python的搜索引擎库,如Google Image Search API和Bing Image Search API,以及Python的图片下载库,如requests和beautifulsoup4。

在Python中,我们可以使用搜索引擎库来搜索图片,然后使用图片下载库来抓取这些图片。下面是一些可用于搜索和下载图片的库:

  1. Google Image Search API
  2. Bing Image Search API
  3. BeautifulSoup
  4. Requests
    下面是一个使用Google Image Search API和Requests库来搜索并下载图片的示例代码:
    首先,你需要安装requests库,可以使用以下命令进行安装:
    1. pip install requests
    然后,你可以使用以下代码来搜索并下载图片:
    1. import requests
    2. from bs4 import BeautifulSoup
    3. def search_and_download_images(keyword, num_results=10):
    4. # 构造Google Image Search API的请求URL
    5. url = 'https://www.google.com/search?q=' + keyword + '&num=' + str(num_results) + '&tbm=isch'
    6. # 发送GET请求获取网页内容
    7. response = requests.get(url)
    8. # 使用BeautifulSoup解析网页内容
    9. soup = BeautifulSoup(response.text, 'html.parser')
    10. # 找到所有图片的URL
    11. image_urls = []
    12. for result in soup.find_all('div', {'class': 'yuRUbf'}):
    13. img = result.find('img')
    14. if img is not None:
    15. image_urls.append(img['src'])
    16. # 下载图片并保存到本地文件夹中
    17. for i, image_url in enumerate(image_urls):
    18. filename = keyword + '_' + str(i) + '.jpg'
    19. response = requests.get(image_url, stream=True)
    20. with open(filename, 'wb') as f:
    21. for chunk in response.iter_content(chunk_size=1024):
    22. if chunk: # 检查是否有数据可读
    23. f.write(chunk)
    24. print('Images downloaded successfully!')
    在这个示例代码中,我们首先构造了一个Google Image Search API的请求URL,然后使用requests库发送GET请求获取网页内容。接下来,我们使用BeautifulSoup库解析网页内容,找到所有图片的URL,并将它们存储在image_urls列表中。最后,我们使用for循环遍历image_urls列表,下载每个图片并将其保存到本地文件夹中。注意,我们在下载每个图片时使用了with open语句打开文件并使用二进制模式写入数据。