Gok*_*N K 3 javascript linux autoscroll web-scraping
我发现一个网站上有很多高质量的免费图像托管在Tumblr上(它说你想用主题图片做任何事情:P)
我在Ubuntu 12.04LTS上运行.我需要编写一个定期运行的脚本(比如说每天)并只下载之前没有下载过的图像.
附加说明:它有一个javascript自动滚动器,当你到达页面底部时会下载图像.
首先,您必须了解自动滚动脚本的工作原理.最简单的方法是不对javascript进行反向工程,而是查看网络活动.最简单的方法是使用Firebug Firefox插件并查看"Net"面板中的活动.您很快就会看到该网站是按页面组织的:
unsplash.com/page/1
unsplash.com/page/2
unsplash.com/page/3
...
Run Code Online (Sandbox Code Playgroud)
滚动时,脚本会请求下载后续页面.
因此,我们实际上可以编写一个脚本来下载所有页面,解析所有图像的html并下载它们.如果您查看html代码,您会看到图像以漂亮且独特的形式存在:
<a href="http://bit.ly/14nUvzx"><img src="http://31.media.tumblr.com/2ba914db5ce556ee7371e354b438133d/tumblr_mq7bnogm3e1st5lhmo1_1280.jpg" alt="Download / By Tony Naccarato" title="http://unsplash.com/post/55904517579/download-by-tony-naccarato" class="photo_img" /></a>
Run Code Online (Sandbox Code Playgroud)
在<a href包含全分辨率图像的URL.该title属性包含一个很好的唯一URL,它也会导致图像.我们将使用它为图像构建漂亮的唯一名称,比存储图像的名称更好.这个漂亮的唯一名称也将确保没有图像被下载两次.
mkdir imgs
I=1
while true ; do # for all the pages
wget unsplash.com/page/$I -O tmppage
grep '<a href.*<img src.*title' tmppage > tmppage.imgs
if [ ! -s tmppage.imgs ] ; then # empty page - end the loop
break
fi
echo "Reading page $I:"
sed 's/^.*<a href="\([^"]*\)".*title="\([^"]*\)".*$/\1 \2/' tmppage.imgs | while read IMG POST ; do
# for all the images on page
TARGET=imgs/`echo $POST | sed 's|.*post/\(.*\)$|\1|' | sed 's|/|_|g'`.jpg
echo -n "Photo $TARGET: "
if [ -f $TARGET ] ; then # we already have this image
echo "already have"
continue
fi
echo "downloading"
wget $IMG -O $TARGET
done
I=$((I+1))
done
Run Code Online (Sandbox Code Playgroud)
创建一个包装脚本usplash.cron:
#!/bin/bash
export PATH=... # might not be needed, but sometimes the PATH is not set
# correctly in cron-called scripts. Copy the PATH setting you
# normally see under console.
cd YOUR_DIRECTORY # the directory where the script and imgs directory is located
{
echo "========================"
echo -n "run unsplash.sh from cron "
date
./unsplash.sh
} >> OUT.log 2>> ERR.log
Run Code Online (Sandbox Code Playgroud)
然后在crontab中添加此行(在crontab -e控制台上发布后):
10 3 * * * PATH_to_the/unsplash.cron
Run Code Online (Sandbox Code Playgroud)
这将在每天3:10运行脚本.