代码之家  ›  专栏  ›  技术社区  ›  xanderflood

如何在Python中下载谷歌图像搜索结果

  •  23
  • xanderflood  · 技术社区  · 9 年前

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

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

    10 回复  |  直到 4 年前
        1
  •  10
  •   Andriy Ivaneyko    4 年前

    使用 Google Custom Search 为了你想要实现的目标。 看见 @i08英寸 的答案 Python - Download Images from google Image search? 它有很好的描述、脚本示例和库参考。

        2
  •  10
  •   Ru Chern Chong ABHINAV    5 年前

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

    pip install icrawler
    
    from icrawler.builtin import GoogleImageCrawler
    google_Crawler = GoogleImageCrawler(storage = {'root_dir': r'write the name of the directory you want to save to here'})
    google_Crawler.crawl(keyword = 'sad human faces', max_num = 800)
    
        3
  •  7
  •   atif93    7 年前

    要使用Selenium从Google图像搜索中下载任意数量的图像:

    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()
    

    完整代码为 here .

        4
  •  5
  •   Soumya Boral    6 年前

    对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)
    

    资料来源: https://pypi.org/project/icrawler/

        5
  •  3
  •   Vishal Gupta hnvasa    6 年前

    这个怎么样?

    https://github.com/hardikvasa/google-images-download

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


    如果你愿意 每个关键字下载100多张图片 ,则需要安装“selenium”和“chromedriver”。

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

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

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

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

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

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

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

        6
  •  2
  •   rishabhr0y    8 年前

    我一直在使用这个脚本从谷歌搜索下载图片,我一直在用它们训练我的分类器 下面的代码可以下载与查询相关的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
    
        7
  •  1
  •   Rodrigo Laguna    6 年前

    我在努力 this library 既可以用作命令行工具,也可以用作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_images_download

        8
  •  1
  •   Avin_ash    5 年前

    这个问题的一个简单解决方案是安装一个名为 google_images_download

    pip install google_images_download

    使用此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)
    

    调整限制以控制要下载的图像数量

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

    更改 keywords 获取所需输出的字符串

        9
  •  0
  •   Lincoln Lorscheider    9 年前

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

        10
  •  0
  •   Ravi Hirani    6 年前

    我试过很多代码,但没有一个适合我。我在这里发布我的工作代码。希望它能帮助其他人。

    我使用的是Python 3.6版 icrawler

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

    然后运行下面的代码。

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

    代替 keyword krishna 与您想要的文本。

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

    google_crawler = GoogleImageCrawler('path_to_your_folder')