您在这里:首页 > 深入 Python > SOAP Web 服务 > 搜索谷歌 | << >> | ||||
深入 Python从 Python 新手到专家 |
让我们最终转向本章开头看到的示例代码,它做了一些比获取当前温度更有用和令人兴奋的事情。
谷歌提供了一个 SOAP API,用于以编程方式访问谷歌搜索结果。要使用它,您需要注册 Google Web 服务。
访问 http://www.google.com/apis/ 并创建一个谷歌帐户。这只需要一个电子邮件地址。注册后,您将通过电子邮件收到您的 Google API 密钥。每当您调用谷歌的搜索功能时,都需要将此密钥作为参数传递。
同样在 http://www.google.com/apis/ 上,下载 Google Web APIs 开发者工具包。这包括几种编程语言(但不包括 Python)的一些示例代码,更重要的是,它包括 WSDL 文件。
解压缩开发者工具包文件并找到 GoogleSearch.wsdl。将此文件复制到本地驱动器上的某个永久位置。您将在本章稍后用到它。
一旦您拥有了开发者密钥并将 Google WSDL 文件放在了已知位置,就可以开始摆弄 Google Web 服务了。
>>> from SOAPpy import WSDL >>> server = WSDL.Proxy('/path/to/your/GoogleSearch.wsdl')>>> server.methods.keys()
[u'doGoogleSearch', u'doGetCachedPage', u'doSpellingSuggestion'] >>> callInfo = server.methods['doGoogleSearch'] >>> for arg in callInfo.inparams:
... print arg.name.ljust(15), arg.type key (u'http://www.w3.org/2001/XMLSchema', u'string') q (u'http://www.w3.org/2001/XMLSchema', u'string') start (u'http://www.w3.org/2001/XMLSchema', u'int') maxResults (u'http://www.w3.org/2001/XMLSchema', u'int') filter (u'http://www.w3.org/2001/XMLSchema', u'boolean') restrict (u'http://www.w3.org/2001/XMLSchema', u'string') safeSearch (u'http://www.w3.org/2001/XMLSchema', u'boolean') lr (u'http://www.w3.org/2001/XMLSchema', u'string') ie (u'http://www.w3.org/2001/XMLSchema', u'string') oe (u'http://www.w3.org/2001/XMLSchema', u'string')
以下是 doGoogleSearch 函数所有参数的简要说明
>>> from SOAPpy import WSDL >>> server = WSDL.Proxy('/path/to/your/GoogleSearch.wsdl') >>> key = 'YOUR_GOOGLE_API_KEY' >>> results = server.doGoogleSearch(key, 'mark', 0, 10, False, "", ... False, "", "utf-8", "utf-8")>>> len(results.resultElements)
10 >>> results.resultElements[0].URL
'http://diveintomark.org/' >>> results.resultElements[0].title 'dive into <b>mark</b>'
results 对象包含的信息不仅仅是实际的搜索结果。它还包含有关搜索本身的信息,例如搜索花费的时间以及找到的结果数量(即使只返回了 10 个)。谷歌网页界面会显示此信息,您也可以通过编程方式访问它。
>>> results.searchTime0.224919 >>> results.estimatedTotalResultsCount
29800000 >>> results.directoryCategories
[<SOAPpy.Types.structType item at 14367400>: {'fullViewableName': 'Top/Arts/Literature/World_Literature/American/19th_Century/Twain,_Mark', 'specialEncoding': ''}] >>> results.directoryCategories[0].fullViewableName 'Top/Arts/Literature/World_Literature/American/19th_Century/Twain,_Mark'
![]() |
此搜索花费了 0.224919 秒。这还不包括发送和接收实际 SOAP XML 文档所花费的时间。这只是谷歌在收到您的请求后处理它所花费的时间。 |
![]() |
总共有大约 3000 万个结果。您可以通过更改 start 参数并再次调用 server.doGoogleSearch 来一次访问 10 个结果。 |
![]() |
对于某些查询,谷歌还会在 谷歌目录 中返回相关类别的列表。您可以将这些网址附加到 http://directory.google.com/ 以构建指向目录类别页面的链接。 |
<< 使用 WSDL 自省 SOAP Web 服务 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
SOAP Web 服务故障排除 >> |