2012-02-16 98 views
2

有没有可能从命令行Wget页面的标题?Wget页面标题

输入:

$ wget http://bit.ly/rQyhG5 <<code>> 

输出:

If it’s broke, fix it right - Keeping it Real Estate. Home 
+2

您需要解析检索到的html并提取html标题的文本内容。为了理智,不要尝试为此使用正则表达式。 – 2012-02-16 13:33:26

回答

5

这个脚本会给你你需要的东西:

wget --quiet -O - http://bit.ly/rQyhG5 \ 
    | sed -n -e 's!.*<title>\(.*\)</title>.*!\1!p' 

但也有很多的情况下它打破了,包括在页面正文中有一个<title>...</title>,或者标题位于多行上。

这可能是一个好一点:

wget --quiet -O - http://bit.ly/rQyhG5 \ 
    | paste -s -d " " \ 
    | sed -e 's!.*<head>\(.*\)</head>.*!\1!' \ 
    | sed -e 's!.*<title>\(.*\)</title>.*!\1!' 

但你的页面包含以下头部开口,它不适合你的情况:

<head profile="http://gmpg.org/xfn/11"> 

同样,这可能会更好:

wget --quiet -O - http://bit.ly/rQyhG5 \ 
    | paste -s -d " " \ 
    | sed -e 's!.*<head[^>]*>\(.*\)</head>.*!\1!' \ 
    | sed -e 's!.*<title>\(.*\)</title>.*!\1!' 

但还是有办法解决它,包括页面中没有标题/标题。

同样,一个更好的解决方案可能是:

wget --quiet -O - http://bit.ly/rQyhG5 \ 
    | paste -s -d " " \ 
    | sed -n -e 's!.*<head[^>]*>\(.*\)</head>.*!\1!p' \ 
    | sed -n -e 's!.*<title>\(.*\)</title>.*!\1!p' 

,但我相信我们能找到一种方法来打破它。这就是为什么一个真正的XML解析器是正确的解决方案,但作为你的问题被标记为shell,上面它是我可以最好的。

paste和2 sed可以合并成一个sed,但可读性较差。然而,这个版本对多行标题的工作的优势:

wget --quiet -O - http://bit.ly/rQyhG5 \ 
    | sed -n -e 'H;${x;s!.*<head[^>]*>\(.*\)</head>.*!\1!;T;s!.*<title>\(.*\)</title>.*!\1!p}' 

更新

正如在评论中解释,上述最后的sed使用T命令,它是GNU扩展。如果你没有一个兼容的版本,你可以使用:

wget --quiet -O - http://bit.ly/rQyhG5 \ 
    | sed -n -e 'H;${x;s!.*<head[^>]*>\(.*\)</head>.*!\1!;tnext;b;:next;s!.*<title>\(.*\)</title>.*!\1!p}' 

更新2

如上仍然没有工作在Mac上,尝试:

wget --quiet -O - http://bit.ly/rQyhG5 \ 
    | sed -n -e 'H;${x;s!.*<head[^>]*>\(.*\)</head>.*!\1!;tnext};b;:next;s!.*<title>\(.*\)</title>.*!\1!p' 

和/或

cat <<EOF> script 
H 
\$x 
\$s!.*<head[^>]*>\(.*\)</head>.*!\1! 
\$tnext 
b 
:next 
s!.*<title>\(.*\)</title>.*!\1!p 
EOF 
wget --quiet -O - http://bit.ly/rQyhG5 \ 
    | sed -n -f script 

(注意在之前的以避免可变扩展。)

它接缝:next不喜欢以$作为前缀,这可能是一些sed版本中的问题。

+0

太棒了!但是我尝试了最后一个解决方案,并得到:'sed:1:“H; $ {x; s!。* ] *> \(...”:无效的命令代码T'作为错误 – 2012-02-16 17:27:44

+0

'T'是一个用于sed的GNU扩展你可能正在Linux上运行脚本,在这种情况下,你可以通过'; tnext; b;:next;'来更改'; T;'我将更新答案。 – jfg956 2012-02-16 17:31:24

+0

另一个error:'sed:2:“H; $ {x; s!。* ] *> \(...”:意想不到的EOF(正在执行)')运行OSX,但是我在这台机器上酿造了gnu-sed ,那么令人惊讶 – 2012-02-16 17:40:31

0

以下将拉动任何l thinks认为页面的标题,从所有的正则表达式废话中拯救你。假设你正在检索的页面是符合标准的l enough,这不应该中断。

lynx -dump example.com | sed '2q;d'