如果您访问DuckDuck Go API Page,您会发现一些关于使用 API 的注意事项。第一个注释清楚地表明:
由于这是一个零点击信息 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 版本仅包含 results,对于 相关搜索,您必须使用 JavaScript 版本。 (没有html 部分网址)。