如何下载Python中的google图像搜索结果

如何下载Python中的google图像搜索结果,python,image,search-engine,Python,Image,Search Engine,这个问题以前被问过很多次,但所有的答案都至少有几年的历史了,目前都基于ajax.googleapis.com API,不再支持该API 有人知道另一种方法吗?我正在尝试下载大约一百个搜索结果,除了Python API之外,我还尝试了许多桌面、基于浏览器或浏览器插件程序,但都失败了。您需要使用自定义搜索API。这里有一个便利店。我使用urllib2。您还需要从开发人员控制台为您的应用程序创建API密钥。使用来实现您想要实现的目标。 请参阅@i08in的答案,其中有大量描述、脚本示例和库参考。我一直

这个问题以前被问过很多次,但所有的答案都至少有几年的历史了,目前都基于ajax.googleapis.com API,不再支持该API


有人知道另一种方法吗?我正在尝试下载大约一百个搜索结果,除了Python API之外,我还尝试了许多桌面、基于浏览器或浏览器插件程序,但都失败了。

您需要使用自定义搜索API。这里有一个便利店。我使用urllib2。您还需要从开发人员控制台为您的应用程序创建API密钥。

使用来实现您想要实现的目标。
请参阅@i08in的答案,其中有大量描述、脚本示例和库参考。

我一直在使用此脚本从谷歌搜索下载图像,并将其用于训练我的分类器 下面的代码可以下载100个与查询相关的图像

from bs4 import BeautifulSoup
import requests
import re
import urllib2
import os
import cookielib
import json

def get_soup(url,header):
    return BeautifulSoup(urllib2.urlopen(urllib2.Request(url,headers=header)),'html.parser')


query = raw_input("query image")# you can change the query for the image  here
image_type="ActiOn"
query= query.split()
query='+'.join(query)
url="https://www.google.co.in/search?q="+query+"&source=lnms&tbm=isch"
print url
#add the directory for your image here
DIR="Pictures"
header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"
}
soup = get_soup(url,header)


ActualImages=[]# contains the link for Large original images, type of  image
for a in soup.find_all("div",{"class":"rg_meta"}):
    link , Type =json.loads(a.text)["ou"]  ,json.loads(a.text)["ity"]
    ActualImages.append((link,Type))

print  "there are total" , len(ActualImages),"images"

if not os.path.exists(DIR):
            os.mkdir(DIR)
DIR = os.path.join(DIR, query.split()[0])

if not os.path.exists(DIR):
            os.mkdir(DIR)
###print images
for i , (img , Type) in enumerate( ActualImages):
    try:
        req = urllib2.Request(img, headers={'User-Agent' : header})
        raw_img = urllib2.urlopen(req).read()

        cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
        print cntr
        if len(Type)==0:
            f = open(os.path.join(DIR , image_type + "_"+ str(cntr)+".jpg"), 'wb')
        else :
            f = open(os.path.join(DIR , image_type + "_"+ str(cntr)+"."+Type), 'wb')


        f.write(raw_img)
        f.close()
    except Exception as e:
        print "could not load : "+img
        print e

要使用Selenium从Google image search下载任意数量的图像,请执行以下操作:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import json
import urllib2
import sys
import time

# adding path to geckodriver to the OS environment variable
# assuming that it is stored at the same path as this script
os.environ["PATH"] += os.pathsep + os.getcwd()
download_path = "dataset/"

def main():
    searchtext = sys.argv[1] # the search query
    num_requested = int(sys.argv[2]) # number of images to download
    number_of_scrolls = num_requested / 400 + 1 
    # number_of_scrolls * 400 images will be opened in the browser

    if not os.path.exists(download_path + searchtext.replace(" ", "_")):
        os.makedirs(download_path + searchtext.replace(" ", "_"))

    url = "https://www.google.co.in/search?q="+searchtext+"&source=lnms&tbm=isch"
    driver = webdriver.Firefox()
    driver.get(url)

    headers = {}
    headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
    extensions = {"jpg", "jpeg", "png", "gif"}
    img_count = 0
    downloaded_img_count = 0

    for _ in xrange(number_of_scrolls):
        for __ in xrange(10):
            # multiple scrolls needed to show all 400 images
            driver.execute_script("window.scrollBy(0, 1000000)")
            time.sleep(0.2)
        # to load next 400 images
        time.sleep(0.5)
        try:
            driver.find_element_by_xpath("//input[@value='Show more results']").click()
        except Exception as e:
            print "Less images found:", e
            break

    # imges = driver.find_elements_by_xpath('//div[@class="rg_meta"]') # not working anymore
    imges = driver.find_elements_by_xpath('//div[contains(@class,"rg_meta")]')
    print "Total images:", len(imges), "\n"
    for img in imges:
        img_count += 1
        img_url = json.loads(img.get_attribute('innerHTML'))["ou"]
        img_type = json.loads(img.get_attribute('innerHTML'))["ity"]
        print "Downloading image", img_count, ": ", img_url
        try:
            if img_type not in extensions:
                img_type = "jpg"
            req = urllib2.Request(img_url, headers=headers)
            raw_img = urllib2.urlopen(req).read()
            f = open(download_path+searchtext.replace(" ", "_")+"/"+str(downloaded_img_count)+"."+img_type, "wb")
            f.write(raw_img)
            f.close
            downloaded_img_count += 1
        except Exception as e:
            print "Download failed:", e
        finally:
            print
        if downloaded_img_count >= num_requested:
            break

    print "Total downloaded: ", downloaded_img_count, "/", img_count
    driver.quit()

if __name__ == "__main__":
    main()
完整的代码是

这个怎么样

它允许你下载数百张图片,并有大量的过滤器可供选择,以定制你的搜索


如果您希望每个关键字下载100多张图像,则需要安装“selenium”和“chromedriver”

如果您已安装了pip库或运行setup.py文件,Selenium将自动安装在您的计算机上。您的机器上还需要Chrome浏览器。对于chromedriver:

根据您的操作系统下载正确的chromedriver

在Windows或MAC上,如果由于某种原因chromedriver给您带来麻烦,请将其下载到当前目录下并运行该命令

但是,在windows上,chromedriver的路径必须以以下格式给出:

C:\complete\path\to\chromedriver.exe

在Linux上,如果您在安装google chrome浏览器时遇到问题,请参阅本CentOS或Amazon Linux指南或Ubuntu指南


对于所有操作系统,您必须使用'--chromedriver'或'-cd'参数来指定您在计算机中下载的chromedriver的路径。

我尝试了许多代码,但没有一个适合我。我在这里发布我的工作代码。希望它能帮助别人

我使用的是Python版本3.6,使用的是

首先,您需要在您的系统中下载

然后运行下面的代码

from icrawler.examples import GoogleImageCrawler
google_crawler = GoogleImageCrawler()
google_crawler.crawl(keyword='krishna', max_num=100)
google_crawler = GoogleImageCrawler('path_to_your_folder')
关键字
奎师那
替换为所需文本

注意:-下载的图像需要路径。现在我使用了脚本所在的目录。您可以通过下面的代码设置自定义目录

from icrawler.examples import GoogleImageCrawler
google_crawler = GoogleImageCrawler()
google_crawler.crawl(keyword='krishna', max_num=100)
google_crawler = GoogleImageCrawler('path_to_your_folder')

对Ravi Hirani的答案稍加改进最简单的方法是:

from icrawler.builtin import GoogleImageCrawler

google_crawler = GoogleImageCrawler(storage={'root_dir': 'D:\\projects\\data core\\helmet detection\\images'})
google_crawler.crawl(keyword='cat', max_num=100)
来源:

我正在尝试既可以用作命令行工具,也可以用作python库。寻找具有不同标准的图像有很多理由

这些示例取自其文档,将其用作python库:

from google_images_download import google_images_download   #importing the library

response = google_images_download.googleimagesdownload()   #class instantiation

arguments = {"keywords":"Polar bears,baloons,Beaches","limit":20,"print_urls":True}   #creating list of arguments
paths = response.download(arguments)   #passing the arguments to the function
print(paths)   #printing absolute paths of the downloaded images
或作为命令行工具,如下所示:

$ googleimagesdownload --k "car" -sk 'red,blue,white' -l 10

您可以使用
pip install google\u images\u download安装此软件。解决此问题的一个简单方法是安装一个名为

pip安装谷歌图片下载

使用以下python代码

from google_images_download import google_images_download  

response = google_images_download.googleimagesdownload()
keywords = "apple fruit"
arguments = {"keywords":keywords,"limit":20,"print_urls":True}
paths = response.download(arguments)
print(paths)
调整限制以控制要下载的图像数量

但有些图像无法打开,因为它们可能已损坏


更改
关键字
字符串以获得所需的输出

确保首先安装icrawler库,然后使用

pip install icrawler

你试过硒吗?硒解决了!我使用了这个代码,对滚动代码做了一点修改。(直接跳到页面底部不一定会导致延迟加载的页面加载所有图像,所以我让它逐渐滚动。)我接受这一点,因为它肯定回答了这个问题!我还想指出,谷歌的API有一些限制,旨在禁止人们使用它们,例如,像我试图做的那样,自动收集搜索结果,因此这种方法可能会遇到权限问题@摩根·G关于使用硒的建议对我来说非常有效!更好的解决方案是将hardikvasa代码包装到API中,方法是将代码更改为从类而不是独立的python脚本运行。这样就不需要API密钥。API密钥都很好,但它们只是测试的另一块。这只允许下载多达100个图像使用chromedriver您可以从上述库下载数百个图像…它不限于100个。说明在自述文件中。:)有没有办法让它停止跳过没有图像格式的图像?(例如)并以其他方式下载它们?什么是icrawler。示例?当我编写代码时,icrawler版本是0.1.5。我已经修改了代码行。谢谢您指出。@SoumyaBoral:Install
pip Install icrawler==0.1.5
应该是icrawler.builtin import GoogleImageCrawler
中的
。这将在2018年12月生效。我最多可以下载1000张图片