【发布时间】:2020-02-28 20:58:08
【问题描述】:
我想使用以下选项从美国国家航空航天局下载图像。
给定特定日期,脚本应该能够下载该日期发布的图像
给定一个特定的日期,脚本应该能够下载标题、解释文本和学分
给定一个特定的日期,脚本应该能够下载标题、解释文本和学分
以下是我尝试过但功能不完整的代码。
GET_DESCRIPTION="yes"
PICTURES_DIR=~/Pictures
DESCRIPTION_DIR=~
function get_page {
echo "Downloading page to find image"
wget http://apod.nasa.gov/apod/ --quiet -O /tmp/apod.html
grep -m 1 jpg /tmp/apod.html | sed -e 's/<//' -e 's/>//' -e 's/.*=//' -e 's/"//g' -e 's/^/http:\/\/apod.nasa.gov\/apod\//' > /tmp/pic_url
}
function save_description {
if [ ${GET_DESCRIPTION} == "yes" ]; then
echo "Getting description from page"
# Get description
if [ -e $DESCRIPTION_DIR/description.txt ]; then
rm $DESCRIPTION_DIR/description.txt
fi
if [ ! -e /tmp/apod.html ]; then
get_page
fi
echo "Parsing description"
sed -n '/<b> Explanation: <\/b>/,/<p> <center>/p' /tmp/apod.html |
sed -e :a -e 's/<[^>]*>//g;/</N;//ba' |
grep -Ev 'Explanation:' |
tr '\n' ' ' |
sed 's/ /\n\n/g' |
awk 'NF { print $0 "\n" }' |
sed 's/^[ \t]*//' |
sed 's/[ \t]*$//' > $DESCRIPTION_DIR/description.txt
fi
}
TODAY=$(date +'%Y%m%d')
if [ ! -e ~/Pictures/${TODAY}_apod.jpg ]; then
echo "We don't have the picture saved, save it"
get_page
PICURL=`/bin/cat /tmp/pic_url`
echo "Picture URL is: ${PICURL}"
echo "Downloading image"
wget --quiet $PICURL -O $PICTURES_DIR/${TODAY}_apod.jpg
echo "Setting image as wallpaper"
gconftool-2 -t string -s /desktop/gnome/background/picture_filename $PICTURES_DIR/${TODAY}_apod.jpg
save_description
else
get_page
PICURL=`/bin/cat /tmp/pic_url`
echo "Picture URL is: ${PICURL}"
SITEFILESIZE=$(wget --spider $PICURL 2>&1 | grep Length | awk '{print $2}')
FILEFILESIZE=$(stat -c %s $PICTURES_DIR/${TODAY}_apod.jpg)
if [ $SITEFILESIZE != $FILEFILESIZE ]; then
echo "The picture has been updated, getting updated copy"
rm $PICTURES_DIR/${TODAY}_apod.jpg
PICURL=`/bin/cat /tmp/pic_url`
echo "Downloading image"
wget --quiet $PICURL -O $PICTURES_DIR/${TODAY}_apod.jpg
echo "Setting image as wallpaper"
$PICTURES_DIR/${TODAY}_apod.jpg
save_description
else
echo "Picture is the same, finishing up"
fi
fi
拜托我是 bash 的新手,我从 GitHub 找到了上面的代码。这不是我的工作。我可以理解代码中发生了什么,但它没有做我想要的。请帮忙
【问题讨论】:
-
一旦选项 2 起作用,选项 3 应该很简单。但开玩笑的,欢迎来到 Stack Overflow。请查看我们的intro pages,特别注意how to ask a good question 上的页面。你说这段代码没有做你想做的事?它在做什么,你想要它做什么?它是否正确地做任何部分?它做错了什么吗?是在做一些无关紧要的事情,还是根本没有做重要的事情?
-
另外,您使用的是什么操作系统,运行脚本时遇到什么错误? PS:当我在Mac 10.10 + macports上运行脚本时,gconftool-2行失败,因为我没有gconftool-2,但是图片下载部分工作正常。
-
感谢@webb 的回复。我在这里很新,没有时间在页面上探索更多内容。我的下一篇文章会更好。我正在使用Linux。我想在特定的给定日期从美国国家航空航天局下载图像,但目前它正在下载当前日期。
标签: bash awk web-scraping sed grep