| 導航:起始頁 > Dive Into Python > SOAP Web 服務 > 搜索 Google | << >> | ||||
深入 Python :Dive Into Python 中文版Python 從新手到專家 [Dip_5.4b_CPyUG_Release] |
|||||
讓我們回到這章開始時你看到的那段代碼,獲得比當前氣溫更有價值和令人振奮的信息。
Google 提供了一個 SOAP API,以便通過程序進行 Google 搜索。使用它的前提是,你注冊了 Google 網絡服務。
訪問 http://www.google.com/apis/ 并創建一個賬號。唯一的需要是提供一個 E-mail 地址。注冊之后,你將通過 E-mail 收到你的 Google API 許可證 (license key)。你需要在調用 Google 搜索函數時使用這個許可證。
還是在 http://www.google.com/apis/ 上,下載 Google 網絡 APIs 開發工具包 (Google Web APIs developer kit)。它包含著包括 Python 在內的多種語言的樣例代碼,更重要的是它包含著 WSDL 文件。
解壓這個開發工具包并找到 GoogleSearch.wsdl。將這個文件拷貝到你本地驅動器的一個永久地址。在本章后面位置你會用到它。
你有了開發許可證和 Google WSDL 文件之后就可以和 Google 網絡服務打交道了。
>>> 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條結果)。Google 網頁界面中顯示了這些信息,通過程序你也同樣能獲得它們。
>>> 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 文檔的時間,僅僅是 Google 在接到搜索請求后執行搜索所花費的時間。 | |
| 總共有接近 30,000,000 個結果信息。通過讓 start 參數以 10 遞增來重復調用 server.doGoogleSearch,你能夠獲得全部的結果。 | |
| 對于有些請求,Google 還返回一個 Google Directory 中的類別列表。你可以用這些 URLs 到 http://directory.google.com/ 建立到 directory category 頁面的鏈接。 |
<< 以 WSDL 進行 SOAP 內省 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
SOAP 網絡服務故障排除 >> |