更新4:PhantomJS 现在已经过时了,我使用 Selenium 和 Chrome headless 在 Python 中制作了一个新脚本 google-images.py。请参阅此处了解更多详细信息:https://stackoverflow.com/a/61982397/218294
更新3:我修复了脚本以与 phantomjs 2.x 一起使用。
更新2:我修改了脚本以使用 phantomjs。安装起来比较困难,但至少它又可以工作了。http://sam.nipl.net/b/google-images http://sam.nipl.net/b/google-images.js
更新1:不幸的是,这不再有效。看来现在需要 JavaScript 和其他魔法来找到图像所在的位置。这是雅虎图像搜索脚本的一个版本:http://sam.nipl.net/code/nipl-tools/bin/yimg
原答案:我为此拼凑了一些东西。我通常会编写较小的工具并将它们一起使用,但您要求一个 shell 脚本,而不是三打。这是故意密集的代码。
http://sam.nipl.net/code/nipl-tools/bin/google-images
到目前为止似乎效果很好。如果您可以改进它,或者建议任何更好的编码技术(假设它是一个 shell 脚本),请告诉我。
#!/bin/bash
[ $# = 0 ] && { prog=`basename "$0"`;
echo >&2 "usage: $prog query count parallel safe opts timeout tries agent1 agent2
e.g. : $prog ostrich
$prog nipl 100 20 on isz:l,itp:clipart 5 10"; exit 2; }
query=$1 count=${2:-20} parallel=${3:-10} safe=$4 opts=$5 timeout=${6:-10} tries=${7:-2}
agent1=${8:-Mozilla/5.0} agent2=${9:-Googlebot-Image/1.0}
query_esc=`perl -e 'use URI::Escape; print uri_escape($ARGV[0]);' "$query"`
dir=`echo "$query_esc" | sed 's/%20/-/g'`; mkdir "$dir" || exit 2; cd "$dir"
url="http://www.google.com/search?tbm=isch&safe=$safe&tbs=$opts&q=$query_esc" procs=0
echo >.URL "$url" ; for A; do echo >>.args "$A"; done
htmlsplit() { tr '\n\r \t' ' ' | sed 's/</\n</g; s/>/>\n/g; s/\n *\n/\n/g; s/^ *\n//; s/ $//;'; }
for start in `seq 0 20 $[$count-1]`; do
wget -U"$agent1" -T"$timeout" --tries="$tries" -O- "$url&start=$start" | htmlsplit
done | perl -ne 'use HTML::Entities; /^<a .*?href="(.*?)"/ and print decode_entities($1), "\n";' | grep '/imgres?' |
perl -ne 'use URI::Escape; ($img, $ref) = map { uri_unescape($_) } /imgurl=(.*?)&imgrefurl=(.*?)&/;
$ext = $img; for ($ext) { s,.*[/.],,; s/[^a-z0-9].*//i; $_ ||= "img"; }
$save = sprintf("%04d.$ext", ++$i); print join("\t", $save, $img, $ref), "\n";' |
tee -a .images.tsv |
while IFS=$'\t' read -r save img ref; do
wget -U"$agent2" -T"$timeout" --tries="$tries" --referer="$ref" -O "$save" "$img" || rm "$save" &
procs=$[$procs + 1]; [ $procs = $parallel ] && { wait; procs=0; }
done ; wait
特征:
- 小于 1500 字节
- 解释用法(如果不带参数运行)
- 并行下载完整图像
- 安全搜索选项
- 图像大小、类型等 opts 字符串
- 超时/重试选项
- 冒充googlebot获取所有图片
- 数字图像文件
- 保存元数据
我将在某个时候发布一个模块化版本,以表明使用一组 shell 脚本和简单的工具可以很好地完成它。