标签:children training 老男孩 linux 网页
对抓取网页的脚本http://life2death.blog.51cto.com/7550586/1657133 的研究:
声明:本人只是拿来学习研究,谢谢浮夸往事大神。
一道企业shell编程实战题 http://oldboy.blog.51cto.com/2561410/1657042
本脚本对http://edu.51cto.com/的视频具有通用性,暂未发现bug,如有发现,请看官自行解决。
---------------------------------------------------------------------------------
#!/bin/bash
# oldboy linux training
# 2015-06-01
# Happy Children‘s Day
# 说明:本脚本来自老男孩linux21期学员张耀开发!
EduFile=/tmp/edu.html ##定义文件来存放网页的HTML源码
EduFile2=/tmp/edu2.html
Url="$*" ##网址参数
# Judge url is ok?
curl -I $Url &>/dev/null ##对网址进行一个测试,看网址是否能连通
[ $? -ne 0 ] &&{
echo "Bad url,Please check it"
exit 1 ##如果不能连上的话,直接中断退出,不再执行后面的步骤
}
# Defined get pagenum and CourseId Functions
function getnum(){ ##这个函数主要用于抽取网址页面的视频的总页数
curl -s $Url>$EduFile
grep ‘"pagesGoEnd"‘ $EduFile &>/dev/null ##用于检测这个视频是否已经完结##51cto中完结了的视频和正在更新的视频html代码如下图:
已完成的视频,会标有pagesGoEnd:
正在更新的视频,最后一页的页码带有“#”:
if [ $? -eq 0 ] ##如果视频是已经更新玩的话,进行下面的抽取页码。 then num=`sed -rn ‘s#.*page=([0-9].*)" class="pagesGoEnd".*$#\1#gp‘ $EduFile`
####
sed:
-r 表支持延伸式的正则表达式,-n 表静默输出。
s///gp :s表替换,g表全局,p打印出被匹配到的行(与n连用)
\1 :表示引用第一个括号里的内容;page=([0-9].*) 引用这里的括号里的内容,从而打印出数字,也就是视频的页数。
else ##表示视频还处于跟新的状态,进行下面的取页数
num=`sed -rn ‘s|.*page=([0-9].*)#" class="pagesNum".*$|\1|gp‘ $EduFile`
fi
pagenum=${num:-1} ##表如果num不存在或为空的时候,则取后面的值,即1,而":-"是固定符号
CourseId=`echo $Url|awk -F "[-.]" ‘{print $4}‘` ##取课程号,
}
课程编号如:
# Defined curl html Functions
function Curl(){ ##将每页的课程代码存放到/tmp/edu.html中
getnum
for i in `seq $pagenum`
do
curl "http://edu.51cto.com/index.php?do=course&m=lessions&course_id=$CourseId&page=$i" 1>>$EduFile 2>/dev/null
done}
###http://edu.51cto.com/index.php?do=course&m=lessions&course_id=839&page=1
这个链接打开的页面如下:(这样就达到一页一页的打开视频页)
# Defined Create table Functions
function table(){
sum=""
index=1
sed -rn ‘/do=lesson/ s#<.*(<a href=")(.*)</h4>$#\1http://edu.51cto.com\2#gp‘ $EduFile > $EduFile2 ##抽取每个视频的网址和其对应的标题抽取的部分如下:
while read line do sum=$sum"<tr><th width="40" scope="row">$index</th><td width="520">$line</td>" ((index++)) ##统计有多少个视频 done <$EduFile2 ##对抽取的网址和标题进行重新的编排。 }
编排效果如下:
# Defined Create html Functions
function html(){
cat >/tmp/oldboy.html<<-END
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
</head>
<body>
<table width="560" border="1">
$sum ##将表格嵌入到网页中
</table>
</body>
</html>
END
}
function main(){
Curl
table
html
}
main本文出自 “天道酬勤” 博客,请务必保留此出处http://luzhi1024.blog.51cto.com/8845546/1657977
标签:children training 老男孩 linux 网页
原文地址:http://luzhi1024.blog.51cto.com/8845546/1657977