在Shell脚本中获取第一个Google搜索结果的URL

问题描述:

使用脚本语言解析AJAX API的输出相对容易:

It's relatively easy to parse the output of the AJAX API using a scripting language:

#!/usr/bin/env python

import urllib
import json

base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
query = urllib.urlencode({'q' : "something"})
response = urllib.urlopen(base + query).read()
data = json.loads(response)
print data['responseData']['results'][0]['url']

但是,有什么更好的方法可以通过基本的shell脚本执行类似的操作?如果您只是卷曲API页面,应该如何编码URL参数或解析JSON?

But are there any better ways to do something similar with just basic shell scripting? If you just curled the API page, how should you encode the URL parameters or parse JSON?

我最终使用curl的--data-urlencode选项对查询参数进行编码,并仅使用sed来提取第一个结果.

I ended up using curl's --data-urlencode option to encode the query parameter and just sed for extracting the first result.

curl -s --get --data-urlencode"q = example" http://ajax.googleapis.com/ajax/services/search/web?v=1.0 |sed's/"unescapedUrl":"\([^"] * \).*/\ 1/; s/.* GwebSearch,//'