从html源抓取文本

时间:2013-09-02 03:36:36

标签: shell unix wget

#!/bin/sh

URL1=http://runescape.com/title.ws
tot=`wget  -qO- $URL1  | grep -i PlayerCount | cut -d\> -f4 | cut -d\< -f1 | sed -e's/,//'`
URL2=http://oldschool.runescape.com
b=`wget -qO- $URL2| grep "people playing" | awk '{print $4}'`
a=`expr $tot - $b`
export LC_ALL=en_US.UTF-8
a_with_comma=`echo $a | awk "{printf \"%'d\n\", \\$1}"`
echo "$a_with_comma people `date '+%r %b %d %Y'`"

这会从URL1和URL2中获取2个数字,并从URL2中减去URL1。试图从http://www.runescape.com/title.ws(URL1)

获取“48,877在线玩家”

URL2工作正常我无法获取URL1。

2 个答案:

答案 0 :(得分:1)

你可以改变......

tot=`wget  -qO- $URL1  | grep -i PlayerCount | cut -d\> -f4 | cut -d\< -f1 | sed -e's/,//'`

...到......

 tot=`wget  -qO- $URL1 | grep -i playercount | cut -d\> -f5 | cut -d\< -f1 | sed -e's/,//'`

......如果你赶时间的话。否则你可能想要遵循tripleee的建议。谁知道你可能会从ACM获得奖励: - )

答案 1 :(得分:1)

这是一个快速尝试将原始内容重构为两个awk实例,以摆脱大多数扭曲。

#!/bin/sh

#URL1=http://runescape.com/title.ws
#tot=$(wget -qO- "$URL1" | awk 'tolower($0) ~ /playercount/ {
#    # Trim anything after this expression
#    gsub(/<\/span> Players Online Now<\/span>.*/, "")
#    # From the remainder, trim anything up through last tag close
#    gsub(/.*>/, "")
#    # Should be left with a number.  Remove any thousands separator
#    gsub(/,/, "")
#    # Should have a computer-readable number now.  Print it
#    print }')
URL0='http://www.runescape.com/c=eWHvvLATbvs/player_count.js?varname=iPlayerCount&callback=jQuery17201610493347980082_1378103074657&_=1378103197632'
tot=$(wget -qO- "$URL0" | awk -F '[()]' '{ print $2 }'

URL2=http://oldschool.runescape.com
wget -qO- "$URL2" | awk -v tot=$tot -v fmt="%'d people " '
    /people playing/ { printf(fmt, tot-$4 )}'
date '+%r %b %d %Y'

URL1的处理现在应该更加强大,因为它会查找span后跟Players Online Now。他们可以随时改变页面的格式,当然这会再次破坏。因此,如果他们提供JSON API,可能会更好。 (简短的谷歌搜索表明这存在,但没有记录。主要文档似乎在http://services.runescape.com/m=rswiki/en/Grand_Exchange_APIs,但这与摘要玩家统计数据无关。)

当然,评论并非绝对必要。如果页面的来源再次发生变化,它们应该帮助你找出要改变的内容,因此修剪它们并不是一个好主意,除非你足够好地学习Awk而不需要它们。

编辑:已更新为使用JSON API获取总玩家数量 - 这应该更加强大,而且更加简单。为了以防万一,我将原始代码留下了评论。