编辑 我现在意识到 API 根本不够用,甚至无法正常工作。 我想重定向我的问题,我希望能够使用他们的“我感觉很鸭”来自动神奇地搜索 duckduckgo。例如,这样我就可以搜索“stackoverflow”并获得主页(“https://stackoverflow.com/”)作为我的结果。
我正在使用 duckduckgo API。 Here
我发现在使用时:
r = duckduckgo.query("example")
结果不反射(reflect)手动搜索,即:
for result in r.results:
print result
结果:
>>>
>>>
没有。
在 results
中查找索引会导致越界错误,因为它是空的。
我应该如何获得搜索结果?
似乎 API(根据其记录的示例)应该以 r.answer.text
的形式回答问题并给出一种“我感觉很笨”的感觉。
但该网站的制作方式使我无法使用正常方法对其进行搜索和解析结果。
我想知道应该如何使用此 API 或本网站的任何其他方法解析搜索结果。
谢谢。
最佳答案
如果您访问 DuckDuck Go API Page ,您会发现一些有关使用 API 的注意事项。第一个注释清楚地表明:
As this is a Zero-click Info API, most deep queries (non topic names) will be blank.
这是这些字段的列表:
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 版本有不同的链接:
- http://duckduckgo.com/?q=example # JavaScript 版本
- http://duckduckgo.com/html/?q=example # 纯 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
变量中存储的结果是指向搜索引擎输出的第一个结果(不是相关搜索)的链接:
要获取所有链接,您可以迭代找到的标签(可以通过类似方式接收除链接以外的其他数据)
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
部分)。
关于python - duckduckgo API 不返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11722465/