使用命令行从谷歌下载图像

时间:2015-01-12 19:41:56

标签: linux shell web

我想下载谷歌给我命令行的第n张图片,例如命令wget

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

5 个答案:

答案 0 :(得分:19)

首次尝试

首先,您需要设置用户代理,以便google授权搜索输出。然后我们可以查找图像并选择所需的图像。为了实现这一点,我们插入缺少的换行符,wget将在一行上返回谷歌搜索,并过滤链接。该文件的索引存储在变量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在寻找'真棒'时应该包含第五张google图片。如果您遇到任何错误,请告诉我,我会照顾它们。

更好的代码

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

#! /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

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

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

使用示例:

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

答案 1 :(得分:7)

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

谷歌最近改变了他们的图片搜索结果页面的网页代码,不幸的是,该网页破坏了贝类的代码。我每天晚上都在一个cron工作中使用它,直到大约4天前它停止接收搜索结果。在研究这个问题时,我发现谷歌已经删除了像imgurl这样的元素,并且已经将更多内容转移到了javascript中。

我的解决方案是扩展了贝类的优秀代码,但对其进行了修改以处理这些Google更改,并包含了一些增强功能&#39;我自己的。

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

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

谢谢。

答案 2 :(得分:1)

从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

答案 3 :(得分:0)

至于搁置的回答

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月

答案 4 :(得分:0)

简单的解决方案,适用于文件&lt;仅4 MB(否则会出现TLS错误):

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