shell 获取搜索引擎结果(一) 百度

作者:shen 发布时间:May 29, 2011 分类:Linux,Shell

方法是用curl获取搜索页面,然后再提取其中的有用信息:
使用时传入一个参数:要搜索的关键词
由于百度默认输出为gb2312编码,最后将编码转为utf-8
#!/bin/bash
search_result=`curl -A Mozilla "http://www.baidu.com/s?ie=utf-8&wd=$1"`
#相关搜索
rel=`echo "$search_result" | sed -n '/<div id="rs">/{:a;n;/<div id="search">/q;p;ba}'|\
sed 's/<[^>]*>//g'|sed '/^[[:space:]]*$/d'|tr "\n" ","|iconv -f gbk -t utf-8`
#搜到的条目数量
num=`echo "$search_result" |grep '<p id="page">'|awk -F'[<>]' '{for(i=1;i<=NF;i++) print $i}' |\
sed -n '/span class="nums"/{n;p;}' |grep -o '[0-9]' |awk '{printf("%d",$0)}'`
#搜索提示
tip=`echo "$search_result" |\
sed -n '/<p style="margin:0 15px 10px"><strong class=f14>.*<span  class="jc">/{:a;n;/<\/span><\/strong><br><\/p>/q;p;ba}'|\
sed '/^[[:space:]]*$/d;s/<[^>]*>//g;s/&nbsp;//g'|\
tr "\n" ","|iconv -f gbk -t utf-8`
echo "$1"
echo "=========="
echo "搜索提示  $tip"
echo "共搜到  $num 条结果"
echo "相关搜素  $rel"
echo "======="
#前几条搜索结果,id="1" 到<p id="page">
echo "$search_result" |sed -n '/id="1"/,/<p id="page">/p'|tr -d "\r"|tr -d "\n"|sed 's/<table [^>]*>/\
/g'|sed '/baike\.baidu\.com/d'|sed '/dict\.baidu\.com/d'|\
sed '/^[[:space:]]*$/d'|egrep '<h3'|\
sed 's/.*<h3 class="t">\(.*\)<\/h3>.*<span class="g">/\1\t---\t/'|awk -F'<\/span>' '{print $1}'|\
sed 's/<[^>]*>//g'|iconv -f gbk -t utf-8
echo "=========="
echo ""

标签: none

添加新评论 »