duckduckgo API不返回结果

Inb*_*ose 13 python api search parsing

编辑我现在意识到API简直不够,甚至没有工作.我想重定向我的问题,我希望能够使用他们的"我感觉很难"来自动神奇地搜索duckduckgo.因此,我可以搜索"stackoverflow",并获取主页(" https://stackoverflow.com/ ")作为我的结果.

我正在使用duckduckgo API.这里

我发现使用时:

r = duckduckgo.query("example")
Run Code Online (Sandbox Code Playgroud)

结果不反映手动搜索,即:

for result in r.results:
    print result
Run Code Online (Sandbox Code Playgroud)

结果是:

>>> 
>>> 
Run Code Online (Sandbox Code Playgroud)

没有.

并在results结果中查找索引错误,因为它是空的.

我怎么能得到搜索结果?

似乎API(根据其记录的例子)应该回答问题并给出一种"我感觉很难吃"的形式 r.answer.text

但是网站是以这样的方式制作的,我无法使用普通方法搜索它并解析结果.

我想知道我应该如何使用此API或本网站的任何其他方法解析搜索结果.

谢谢.

Ros*_*nko 29

如果您访问DuckDuck Go API页面,您会发现有关使用API​​的一些注意事项.第一个笔记清楚地表明:

由于这是零点击Info API,因此大多数深层查询(非主题名称)将为空白.

这是这些字段的列表:

Abstract: ""
AbstractText: ""
AbstractSource: ""
AbstractURL: ""
Image: ""
Heading: ""
Answer: ""
Redirect: ""
AnswerType: ""
Definition: ""
DefinitionSource: ""
DefinitionURL: ""
RelatedTopics: [ ]
Results: [ ]
Type: ""
Run Code Online (Sandbox Code Playgroud)

所以它可能是一个遗憾,但他们的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
Run Code Online (Sandbox Code Playgroud)

这个脚本打印:

u'Eixample, an inner suburb of Barcelona with distinctive architecture'
Run Code Online (Sandbox Code Playgroud)

在主页面上直接查询的问题是它使用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']
Run Code Online (Sandbox Code Playgroud)

存储在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
...
Run Code Online (Sandbox Code Playgroud)

请注意,仅HTML版本仅包含结果,对于相关搜索,您必须使用JavaScript版本.(不在html网址中的部分).