用Python搜索谷歌

Hic*_*ick 7 python ms-word google-api

如何使用Python在Google上执行搜索查询?如何将搜索结果存储在Microsoft Word文档中?

mar*_*cog 16

使用提供的API.首先登记,以获得API密钥这里.然后你可以使用Python的urllib2包来获取结果,例如

import urllib2
import json
import pprint
data = urllib2.urlopen('https://www.googleapis.com/customsearch/v1?key=YOUR_KEY_HERE&cx=017576662512468239146:omuauf_lfve&q=lectures')
data = json.load(data)
pprint.PrettyPrinter(indent=4).pprint(data['items'][0]) # Print the raw content of the first result
Run Code Online (Sandbox Code Playgroud)

哪个输出

{   'cacheid': 'TxVqFzFZLOsJ',
    'displayLink': 'www.stanford.edu',
    'htmlSnippet': 'Apr 7, 2010 \\u003cb\\u003e...\\u003c/b\\u003e Course materials. \\u003cb\
\u003eLecture\\u003c/b\\u003e slides \xc2\xb7 \\u003cb\\u003eLecture\\u003c/b\\u003e videos (2
008) \xc2\xb7 Review sessions. \\u003cbr\\u003e  Assignments. Homework \xc2\xb7 Reading. Exams
. Final exam \\u003cb\\u003e...\\u003c/b\\u003e',
    'htmlTitle': 'EE364a: \\u003cb\\u003eLecture\\u003c/b\\u003e Videos',
    'kind': 'customsearch#result',
    'link': 'http://www.stanford.edu/class/ee364a/videos.html',
    'snippet': 'Apr 7, 2010 ... Course materials. Lecture slides \xc2\xb7 Lecture videos (2008
) \xc2\xb7 Review sessions.   Assignments. Homework \xc2\xb7 Reading. Exams. Final exam ...',
        'title': 'EE364a: Lecture Videos'}
Run Code Online (Sandbox Code Playgroud)

请务必以取代YOUR_KEY_HERE你的密钥.

要从Python创建MS Word文档,请阅读此问题.

  • 这个答案很危险.它将在某些(罕见)响应中中断,并且它包含远程代码执行安全性错误.(marcog:我知道你已经把"!当心的eval()荷兰国际集团不可信数据"的评论有,但也有很多人谁都会忽略了警告,因为"它的工作原理,我为什么要改变它"然后,他们会写危险的代码).另请参见http://stackoverflow.com/questions/1083250/running-json-through-pythons-eval (2认同)
  • 是的,当你可以使用更安全的`json.load()`时,为什么要使用`eval()`? (2认同)
  • @ user9876 @Aphex更改了答案.我对Python中的json处理不是很熟悉,所以感谢你指出这一点. (2认同)

Aph*_*hex 3

http://code.google.com/apis/customsearch/v1/getting_started.html

http://code.google.com/apis/customsearch/v1/using_rest.html

Google 的自定义搜索 API 看起来正是您所寻找的。您需要先获取 API 密钥;那么他们似乎允许你每天进行最多 100 次搜索。

用于urllib2获取 URL 并simplejson对其进行解码。(如果您还没有这些软件包,请在 Google 上搜索它们。)您可以使用它将json.load()响应转换为可以轻松读取的 Python 字典。快乐黑客!

编辑:至于创建Word文档,您有多种选择,详细信息请参见:How can I create a Word document using Python?


归档时间:

查看次数:

8447 次

最近记录:

8 年,1 月 前