Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 从谷歌搜索下载前1000张图片_Regex_Image_Shell_Uri - Fatal编程技术网

Regex 从谷歌搜索下载前1000张图片

Regex 从谷歌搜索下载前1000张图片,regex,image,shell,uri,Regex,Image,Shell,Uri,我搜索了一些谷歌图片 结果是成千上万张照片。我正在寻找一个shell脚本,它将下载第一批n图像,例如1000或500 我该怎么做 我想我需要一些高级正则表达式之类的东西。我尝试了很多东西,但都没有用,有人能帮我吗?我认为单靠正则表达式无法完成整个任务。这个问题有三个部分- 1提取所有图像的链接------>无法使用正则表达式。为此,您需要使用基于web的语言。谷歌有API可以通过编程实现这一点。退房并离开 2。假设您使用某种基于web的语言成功完成了第一步,您可以使用下面的正则表达式,该正则表

我搜索了一些谷歌图片

结果是成千上万张照片。我正在寻找一个shell脚本,它将下载第一批
n
图像,例如1000或500

我该怎么做


我想我需要一些高级正则表达式之类的东西。我尝试了很多东西,但都没有用,有人能帮我吗?

我认为单靠正则表达式无法完成整个任务。这个问题有三个部分-

1提取所有图像的链接------>无法使用正则表达式。为此,您需要使用基于web的语言。谷歌有API可以通过编程实现这一点。退房并离开

2。假设您使用某种基于web的语言成功完成了第一步,您可以使用下面的正则表达式,该正则表达式使用lookaheads提取准确的图像URL

(?<=imgurl=).*?(?=&)

(?与使用regexp在shell中执行此操作相比,如果您使用能够实际解析HTML本身的东西,例如,可能会更容易

如果你只能使用shell,并且需要模糊图像URL,你可能不会完全不走运,因为HTML不是一个简单的语言。但是如果你的输入数据是高度可预测的,你仍然可以过得去。(这是没有保证的,因为谷歌会定期更新他们的产品和服务,而且通常不会事先宣布。)

也就是说,在您在问题中提供的URL输出中,每个图像URL似乎都嵌入到链接到
/imgres?..
的锚点中。如果我们可以解析这些链接,我们可能可以从中收集我们需要的内容。在这些链接中,图像URL前面似乎有
&;imgurl=
。所以让我们来解决这个问题

#!/usr/local/bin/bash

# Possibly violate Google's terms of service by lying about our user agent
agent="Mozilla/5.0 (X11; FreeBSD amd64; rv:12.0) Gecko/20100101 Firefox/12.0"

# Search URL
url="http://www.google.com/search?hl=en&q=panda&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&biw=1287&bih=672&um=1&ie=UTF-8&tbm=isch&source=og&sa=N&tab=wi&ei=qW4FUJigJ4jWtAbToInABg"

curl -A "$agent" -s -D- "$url" \
 | awk '{gsub(/<a href=/,"\n")} 1' \
 | awk '
   /imgres/ {
     sub(/" class=rg_l >.*/, "");       # clean things up
     split($0, fields, "\&amp;");       # gather the "GET" fields
     for (n=1; n<=length(fields); n++) {
       split(fields[n], a, "=");        # split name=value pair
       getvars[a[1]]=a[2];              # store in array
     }
     print getvars["imgurl"];           # print the result
   }
 '

请注意,当我使用您在问题中指定的搜索URL运行此程序时,Google似乎只向我提供了83个结果(不是1000个)。这可能只是Google通常在“扩展”页面(使用JavaScript)之前向浏览器分发的第一个页面当我接近底部时,正确的处理方法是使用谷歌的搜索API,根据Pavan的回答,如果你每天搜索超过100次,就支付谷歌的数据。

< P>而不是试图解析HTML(这是非常困难的,很可能会被打破),考虑API在答案中突出显示。

另外,考虑使用一个已经尝试做类似事情的工具。WGET(WebGET)有一个类似于蜘蛛的特性来跟踪链接(特别是针对指定的文件类型)。 正则表达式非常有用,但我不认为它在这种情况下有用——记住正则表达式的咒语:

有些人在遇到问题时会想“我知道,我会使用正则表达式。”现在他们有两个问题

--杰米·扎温斯基


更新4:PhantomJS现在已经过时,我使用Selenium和Chrome headless在Python中创建了一个新脚本google-images.py。有关更多详细信息,请参见此处:

更新3:我修复了使用phantomjs 2.x的脚本

更新2:我修改了脚本以使用phantomjs。安装起来比较困难,但至少可以再次使用

更新1:不幸的是,这不再有效。现在似乎需要Javascript和其他魔法才能找到图像的位置。以下是用于yahoo图像搜索的脚本版本:

原始答案:为此,我把一些东西拼凑在一起。我通常编写较小的工具并一起使用,但你要求的是一个shell脚本,而不是三打。这是故意编写的密集代码

到目前为止,它似乎工作得很好。请告诉我您是否可以改进它,或者建议任何更好的编码技术(考虑到它是一个shell脚本)

!/bin/bash
[$#=0]&&{prog=`basename“$0”`;
echo>&2“用法:$prog query count并行安全选项超时尝试agent1 agent2
e、 g.:$prog鸵鸟
$prog nipl 100 20关于isz:l,itp:clipart 5 10“出口2;}
查询=$1计数=${2:-20}并行=${3:-10}安全=$4选项=$5超时=${6:-10}尝试=${7:-2}
agent1=${8:-Mozilla/5.0}agent2=${9:-Googlebot Image/1.0}
query_esc=`perl-e'使用URI::Escape;打印URI_Escape($ARGV[0]);“$query”`
dir=`echo“$query_esc”| sed's/%20/-/g`;mkdir“$dir”|退出2;cd“$dir”
url=”http://www.google.com/search?tbm=isch&safe=$safe&tbs=$opts&q=$query\u esc“procs=0
echo>.URL“$URL”用于A;do echo>.args“$A”完成
htmlsplit(){tr'\n\r\t'''| sed's/\n/g;s/\n*\n/\n/g;s/^*\n/;s/$/;}
对于'seq 0 20$[$count-1]`do;中的开头
wget-U“$agent1”-T“$timeout”-tries=“$trys”-O-”$url&start=$start”| htmlsplit

完成| perl-ne'使用HTML::Entities;/^和Pavan Manjunath的响应,如果您想要图像的高度和宽度


(?这么多工作量?为什么不使用批量图像下载程序?
它有100个图像限制


需要为具有Java图像查看器的站点编码。

github上还有其他库-这看起来相当不错


我找到了一个更简单的方法来处理这个问题,我可以确认它和这篇文章一样有效。

向开发人员发出的功能请求:

  • 获取图像预览以验证其正确性
  • 允许按顺序输入多个术语(即批处理)

Python脚本:从谷歌图像搜索下载全分辨率图像 目前,它每查询下载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="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
我在这里重新发布我的解决方案,这是我在下面问题上发布的原始解决方案
使用这个库怎么样


对于仍在寻找下载100张图片的合适方法的人,可以使用此命令行参数代码。

我使用此代码下载了1000张图片,它100%适用于我:

下载后,打开终端并安装Selenium

$ pip install selenium --user
然后检查您的python版本

$ python --version
如果运行的是
Python2.7
,则转到downloa
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="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
$ pip install selenium --user
$ python --version
$ python image_download_python2.py 'pizza' '1000'
$ python image_download_python3.py 'pizza' '1000'
python image_download_python2.py <query> <number of images>
python image_download_python3.py <query> <number of images>