【问题标题】:download images from google with command line [closed]使用命令行从谷歌下载图像[关闭]
【发布时间】:2015-03-10 15:56:05
【问题描述】:

我想下载谷歌通过命令行提供给我的第 n 个图像,例如使用命令 wget

要搜索[something] 的图像,我只需转到页面https://www.google.cz/search?q=[something]&tbm=isch,但是如何获取第n 个搜索结果的url 以便我可以使用wget?

【问题讨论】:

  • 为什么这个问题被关闭了?我不明白我得到的解释:“我们不允许在 Stack Overflow 上提出有关通用计算硬件和软件的问题”这如何适用,尤其是当这个问题在这里愉快地生活了 6 年时。

标签: linux shell web


【解决方案1】:

第一次尝试

首先,您需要设置用户代理,以便 google 授权搜索的输出。然后我们可以查找图像并选择所需的图像。为了实现这一点,我们插入缺少的换行符,wget 将在一行中返回 google 搜索,并过滤链接。文件的索引存储在变量count中。

$ count=10
$ imagelink=$(wget --user-agent 'Mozilla/5.0' -qO - "www.google.be/search?q=something\&tbm=isch" | sed 's/</\n</g' | grep '<img' | head -n"$count" | tail -n1 | sed 's/.*src="\([^"]*\)".*/\1/')
$ wget $imagelink 

图像现在将在您的工作目录中,您可以调整最后一个命令并指定所需的输出文件名。

你可以在一个shell脚本中总结它:

#! /bin/bash
count=${1}
shift
query="$@"
[ -z $query ] && exit 1  # insufficient arguments
imagelink=$(wget --user-agent 'Mozilla/5.0' -qO - | "www.google.be/search?q=${query}\&tbm=isch" | sed 's/</\n</g' | grep '<img' | head -n"$count" | tail -n1 | sed 's/.*src="\([^"]*\)".*/\1/')
wget -qO google_image $imagelink

示例用法:

$ ls
Documents
Downloads
Music
script.sh
$ chmod +x script.sh
$ bash script.sh 5 awesome
$ ls
Documents
Downloads
google_image
Music
script.sh

现在google_image 在查找“真棒”时应该包含第五张谷歌图片。如果您遇到任何错误,请告诉我,我会处理的。

更好的代码

此代码的问题在于它返回的图片分辨率较低。更好的解决方案如下:

#! /bin/bash

# function to create all dirs til file can be made
function mkdirs {
    file="$1"
    dir="/"

    # convert to full path
    if [ "${file##/*}" ]; then
        file="${PWD}/${file}"
    fi

    # dir name of following dir
    next="${file#/}"

    # while not filename
    while [ "${next//[^\/]/}" ]; do
        # create dir if doesn't exist
        [ -d "${dir}" ] || mkdir "${dir}"
        dir="${dir}/${next%%/*}"
        next="${next#*/}"
    done

    # last directory to make
    [ -d "${dir}" ] || mkdir "${dir}"
}

# get optional 'o' flag, this will open the image after download
getopts 'o' option
[[ $option = 'o' ]] && shift

# parse arguments
count=${1}
shift
query="$@"
[ -z "$query" ] && exit 1  # insufficient arguments

# set user agent, customize this by visiting http://whatsmyuseragent.com/
useragent='Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0'

# construct google link
link="www.google.cz/search?q=${query}\&tbm=isch"

# fetch link for download
imagelink=$(wget -e robots=off --user-agent "$useragent" -qO - "$link" | sed 's/</\n</g' | grep '<a href.*\(png\|jpg\|jpeg\)' | sed 's/.*imgurl=\([^&]*\)\&.*/\1/' | head -n $count | tail -n1)
imagelink="${imagelink%\%*}"

# get file extention (.png, .jpg, .jpeg)
ext=$(echo $imagelink | sed "s/.*\(\.[^\.]*\)$/\1/")

# set default save location and file name change this!!
dir="$PWD"
file="google image"

# get optional second argument, which defines the file name or dir
if [[ $# -eq 2 ]]; then
    if [ -d "$2" ]; then
        dir="$2"
    else
        file="${2}"
        mkdirs "${dir}"
        dir=""
    fi
fi   

# construct image link: add 'echo "${google_image}"'
# after this line for debug output
google_image="${dir}/${file}"

# construct name, append number if file exists
if [[ -e "${google_image}${ext}" ]] ; then
    i=0
    while [[ -e "${google_image}(${i})${ext}" ]] ; do
        ((i++))
    done
    google_image="${google_image}(${i})${ext}"
else
    google_image="${google_image}${ext}"
fi

# get actual picture and store in google_image.$ext
wget --max-redirect 0 -qO "${google_image}" "${imagelink}"

# if 'o' flag supplied: open image
[[ $option = "o" ]] && gnome-open "${google_image}"

# successful execution, exit code 0
exit 0

cmets 应该是不言自明的,如果您对代码有任何疑问(例如长管道),我将很乐意澄清机制。请注意,我必须在 wget 上设置更详细的用户代理,您可能需要设置不同的用户代理,但我认为这不会有问题。如果您确实有问题,请访问http://whatsmyuseragent.com/ 并在useragent 变量中提供输出。

当您希望打开图像而不是仅下载时,请使用-o 标志,示例如下。如果您希望扩展脚本并包含自定义输出文件名,请告诉我,我会为您添加。

示例用法:

$ chmod +x getimg.sh
$ ./getimg.sh 1 dog
$ gnome-open google_image.jpg
$ ./getimg.sh -o 10 donkey

【讨论】:

  • @tom 很高兴,也请查看脚本!
  • 恐怕谷歌没有在他们的网站代码中提供指向原始图像的链接。它必须是处理链接到原始图像的javascript。如果您可以在 google 的代码中找到它(使用浏览器的“检查元素”),我会很乐意处理它。
  • 我弄错了,我会查的。
  • 脚本现在应该接受第二个参数,它是一个目标目录(如果文件已经存在。您也可以提供文件名作为第二个参数,例如/home/user/Documents/images/image。扩展名将自动添加。--如果有错误,请告诉我。
  • @User8547 现在应该已经修复,请报告更多错误。
【解决方案2】:

这是对ShellFish 提供的答案的补充。非常尊重他们解决这个问题。 :)

Google 最近更改了图片结果页面的网络代码,不幸的是,这破坏了 Shellfish 的代码。直到大约 4 天前,当它停止接收搜索结果时,我每晚都在 cron 作业中使用它。在对此进行调查时,我发现 Google 已经删除了诸如 imgurl 之类的元素,并将更多内容转移到了 javascript 中。

我的解决方案是对 Shellfish 出色代码的扩展,但进行了修改以处理这些 Google 更改,并且包括我自己的一些“增强”。

它执行单个 Google 搜索,保存结果,批量下载指定数量的图像,然后使用 ImageMagick 将这些图像构建到单个画廊图像中。最多可以请求 1,000 张图片。

此 bash 脚本位于 https://git.io/googliser

谢谢。

【讨论】:

  • 感谢您更新此内容,如果您同意,我稍后会将您的答案合并到我的答案中。你当然会得到应得的荣誉!
  • 我刚刚检查了脚本,你真的很好。不过,您应该考虑将其移至公共 github 存储库。然后人们可以分叉它并对可能的扩展执行拉取请求。也许它甚至可以最终出现在诸如 Arch 的 AUR 之类的公共存储库中!顺便说一句,感谢您的信任!
  • 感谢贝壳鱼。 :) GitHub 上的好电话。我昨天创建了一个帐户,现在已将脚本上传到公共仓库。我已经更新了指向 GitHub 的链接。现在 - 只需要学习如何使用它!大声笑...
  • 我已经修改了您的代码以在 Mac OSX 上运行:它主要需要安装一些 GNU 实用程序并将它们换成 googliser 中的本机实用程序。你可以找到脚本here
  • 谢谢!它让我可以在 the script 这里找到使用 OpenCV 和 NodeJS 的肖像。
【解决方案3】:

至于陈词滥调的回答

imagelink=$(wget -e robots=off --user-agent "$useragent" -qO - "$link" | sed 's/\"ou\"/\n\"ou\"/g' | grep '\"ou\"\:\".*\(png\|jpg\|jpeg\).*ow\"' | awk -F'"' '{print $4}' | head -n $count|tail -n1)

将与 2016 年 6 月的当前 google 图片搜索一起使用

【讨论】:

    【解决方案4】:

    用于从 Google 下载高分辨率图像的 Python 代码。我在这里发布了原始答案Python - Download Images from google Image search?

    当前根据搜索查询下载 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)))
    
    
    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="C:\\Users\\Rishabh\\Pictures\\"+query.split('+')[0]+"\\"
    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"
    
    
    ###print images
    for i , (img , Type) in enumerate( ActualImages):
        try:
            req = urllib2.Request(img, headers={'User-Agent' : header})
            raw_img = urllib2.urlopen(req).read()
            if not os.path.exists(DIR):
                os.mkdir(DIR)
            cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
            print cntr
            if len(Type)==0:
                f = open(DIR + image_type + "_"+ str(cntr)+".jpg", 'wb')
            else :
                f = open(DIR + image_type + "_"+ str(cntr)+"."+Type, 'wb')
    
    
            f.write(raw_img)
            f.close()
        except Exception as e:
            print "could not load : "+img
            print e
    

    【讨论】:

      【解决方案5】:

      简单的解决方案,仅适用于

      wget --user-agent "Mozilla/5.0" -qO - "$@" |grep video.googleusercontent.com|cut -d'"' -f2|wget --content-disposition -c -i -
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        相关资源
        最近更新 更多