如果你訪問DuckDuck Go API Page,你會發現有關使用API的一些注意事項。第一個註釋清楚地指出:
由於這是一個Zero-click Info API,大多數深度查詢(非主題名稱) 將爲空白。
的下面是這些字段的列表:
Abstract: ""
AbstractText: ""
AbstractSource: ""
AbstractURL: ""
Image: ""
Heading: ""
Answer: ""
Redirect: ""
AnswerType: ""
Definition: ""
DefinitionSource: ""
DefinitionURL: ""
RelatedTopics: [ ]
Results: [ ]
Type: ""
因此,它可能是一個遺憾,但他們的API只是截斷了一堆結果,並沒有給予他們給你;可能會更快地工作,似乎除了使用DuckDuckGo.com之外,什麼都不能做。
因此,很顯然,在這種情況下,API不是要走的路。
至於我,我看到只剩下一條出路:從duckduckgo.com檢索原始html並使用(例如) html5lib(值得一提的是他們的html結構很好)。
值得一提的是,解析html頁面並不是最可靠的報廢數據的方式,因爲html結構可以改變,而API通常保持穩定,直到公佈更改。
這裏是和舉例如何與BeautifulSoup可以這樣解析實現:
from BeautifulSoup import BeautifulSoup
import urllib
import re
site = urllib.urlopen('http://duckduckgo.com/?q=example')
data = site.read()
parsed = BeautifulSoup(data)
topics = parsed.findAll('div', {'id': 'zero_click_topics'})[0]
results = topics.findAll('div', {'class': re.compile('results_*')})
print results[0].text
此腳本會打印:
u'Eixample, an inner suburb of Barcelona with distinctive architecture'
直接查詢的主頁上的問題是,它使用JavaScript來產生所需的結果(不相關的主題),所以你可以使用HTML版本來獲得結果。 HTML的版本有不同的鏈接:
讓我們看看我們可以得到:
site = urllib.urlopen('http://duckduckgo.com/html/?q=example')
data = site.read()
parsed = BeautifulSoup(data)
first_link = parsed.findAll('div', {'class': re.compile('links_main*')})[0].a['href']
存儲在first_link
結果變量是第一個鏈接結果(不是關聯編輯搜索),搜索引擎輸出:
http://www.iana.org/domains/example
要得到所有你可以遍歷的鏈接上找到了標記(其它數據除了鏈接可以收到類似的方式)
for i in parsed.findAll('div', {'class': re.compile('links_main*')}):
print i.a['href']
http://www.iana.org/domains/example
https://twitter.com/example
https://www.facebook.com/leadingbyexample
http://www.trythisforexample.com/
http://www.myspace.com/leadingbyexample?_escaped_fragment_=
https://www.youtube.com/watch?v=CLXt3yh2g0s
https://en.wikipedia.org/wiki/Example_(musician)
http://www.merriam-webster.com/dictionary/example
...
請注意,純HTML版本只包含結果和相關搜索您必須使用JavaScript版本。 (在url中沒有html
部分)。
謝謝。這有助於我理解問題所在,你是從哪裏找到的? :P我試着爲duckduckgo的常規html頁面編寫一個解析器,但是我遇到了問題,因爲它使用java或其他東西,結果沒有以適當的html格式出來...... – 2012-08-13 07:25:05
它對BeautifulSoup適用於我。將更新答案 – 2012-08-13 09:53:53
好,那是錯誤的,你得到的結果是從相關的搜索。 – 2012-08-13 10:01:46