在Shell脚本中获取第一个Google搜索结果的URL [英] Getting the URLs for the first Google search results in a shell script
问题描述
使用脚本语言解析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,//'
这篇关于在Shell脚本中获取第一个Google搜索结果的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!