Shell脚本爬取IMDb影片页异常,未取到剧情摘要且输出冗余追踪内容
Shell脚本开发待解决问题
脚本开发目标
开发一款bash shell脚本,支持两类IMDb影片查询能力:
- 支持用户输入IMDb平台的纯数字影片ID:示例
0076759对应《星球大战:新的希望》,这类ID取自IMDb影片详情页的URL路径 - 支持用户输入影片文本名进行模糊匹配
- 预期运行效果:当用户执行命令
bash search_movie 0076759时,输出内容严格匹配如下格式:Star Wars: Episode IV - A New Hope (1977) Luke Skywalker joins forces with a...[完整剧情摘要文本]
当前已编写的脚本代码
#!/usr/bin/bash # moviedata--Given a movie or TV title, returns a list of matches. If the user # specifies an IMDb numeric index number, however, returns the synopsis of # the film instead. # Remember to install lynx with command: sudo yum install lynx titleurl="http://www.imdb.com/title/tt" imdburl="http://www.imdb.com/find?s=tt&exact=true&ref_=fn_tt_ex&q=" tempout="/tmp/moviedata.$$" # Produce a synopsis of the film. summarize_film() { grep "<title>" $tempout | sed 's/<[^>]*>//g;s/(more)//' grep --color=never -A2 '<h5>Plot:' $tempout | tail -1 | \ cut -d\< -f1 | fmt | sed 's/^/ /' exit 0 } trap "rm -f $tempout" 0 1 15 if [ $# -eq 0 ] ; then echo "Usage: $0 {movie title | movie ID}" >&2 exit 1 fi # Checks whether we're asking for a title by IMDb title number nodigits="$(echo $1 | sed 's/[[:digit:]]*//g')" if [ $# -eq 1 -a -z "$nodigits" ] ; then lynx -source "$titleurl$1/combined" > $tempout summarize_film exit 0 fi # It's not an IMDb title number, search for titles. fixedname="$(echo $@ | tr ' ' '+')" # for the URL url="$imdburl$fixedname" lynx -source $imdburl$fixedname > $tempout # No results: fail="$(grep --color=never '<h1 class="findHeader">No ' $tempout)" # If more than one matching title found: if [ ! -z "$fail" ] ; then echo "Failed: no results found for $1" exit 1 elif [ ! -z "$(grep '<h1 class="findHeader">Displaying' $tempout)" ] ; then grep --color=never '/title/tt' $tempout | \ sed 's/<</g' | \ grep -vE '(.png|.jpg|>[ ]*$)' | \ grep -A 1 "a href=" | \ grep -v '^--$' | \ sed 's/<a href="\/title\/tt//g;s/<\/a> //' | \ awk '(NR % 2 == 1) { title=$0 } (NR % 2 == 0) { print title " " $0 }' | \ sed 's/\/.*>/: /' | \ sort fi exit 0
当前运行存在的异常
脚本已能正常向IMDb发送请求、获取目标页面内容,但存在两类问题:
- 输入纯数字影片ID时,无法正确提取并返回对应影片的剧情摘要
- 最终输出混杂了大量网站追踪类非正文冗余信息

内容的提问来源于stack exchange,提问作者Mana
相关产品推荐
相关产品推荐

