-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathduckduckgo.py
executable file
·164 lines (122 loc) · 4.71 KB
/
duckduckgo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/env python
import urllib
import urllib2
from xml.etree import ElementTree
__version__ = 0.1
def query(query, useragent='python-duckduckgo 0.1'):
"""
Query Duck Duck Go, returning a Results object.
Here's a query that's unlikely to change:
>>> result = query('1 + 1')
>>> result.type
'nothing'
>>> result.answer.text
'1 + 1 = 2'
>>> result.answer.type
'calc'
"""
params = urllib.urlencode({'q': query, 'o': 'x'})
url = 'http://duckduckgo.com/?' + params
request = urllib2.Request(url, headers={'User-Agent': useragent})
response = urllib2.urlopen(request)
xml = ElementTree.fromstring(response.read())
response.close()
return Results(xml)
class Results(object):
def __init__(self, xml):
self.type = {'A': 'answer', 'D': 'disambiguation',
'C': 'category', 'N': 'name',
'E': 'exclusive', '': 'nothing'}[xml.findtext('Type', '')]
self.api_version = xml.attrib.get('version', None)
self.heading = xml.findtext('Heading', '')
self.results = [Result(elem) for elem in xml.getiterator('Result')]
self.related = [Result(elem) for elem in
xml.getiterator('RelatedTopic')]
self.abstract = Abstract(xml)
answer_xml = xml.find('Answer')
if answer_xml is not None:
self.answer = Answer(answer_xml)
if not self.answer.text:
self.answer = None
else:
self.answer = None
image_xml = xml.find('Image')
if image_xml is not None and image_xml.text:
self.image = Image(image_xml)
else:
self.image = None
class Abstract(object):
def __init__(self, xml):
self.html = xml.findtext('Abstract', '')
self.text = xml.findtext('AbstractText', '')
self.url = xml.findtext('AbstractURL', '')
self.source = xml.findtext('AbstractSource')
class Result(object):
def __init__(self, xml):
self.html = xml.text
self.text = xml.findtext('Text')
self.url = xml.findtext('FirstURL')
icon_xml = xml.find('Icon')
if icon_xml is not None:
self.icon = Image(icon_xml)
else:
self.icon = None
class Image(object):
def __init__(self, xml):
self.url = xml.text
self.height = xml.attrib.get('height', None)
self.width = xml.attrib.get('width', None)
class Answer(object):
def __init__(self, xml):
self.text = xml.text
self.type = xml.attrib.get('type', '')
def main():
import sys
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] query",
version="ddg %s" % __version__)
parser.add_option("-o", "--open", dest="open", action="store_true",
help="open results in a browser")
parser.add_option("-n", dest="n", type="int", default=3,
help="number of results to show")
parser.add_option("-d", dest="d", type="int", default=None,
help="disambiguation choice")
(options, args) = parser.parse_args()
q = ' '.join(args)
if options.open:
import urllib
import webbrowser
webbrowser.open("http://duckduckgo.com/?%s" % urllib.urlencode(
dict(q=q)), new=2)
sys.exit(0)
results = query(q)
if options.d and results.type == 'disambiguation':
try:
related = results.related[options.d - 1]
except IndexError:
print "Invalid disambiguation number."
sys.exit(1)
results = query(related.url.split("/")[-1].replace("_", " "))
if results.answer and results.answer.text:
print "Answer: %s\n" % results.answer.text
elif results.abstract and results.abstract.text:
print "%s\n" % results.abstract.text
if results.type == 'disambiguation':
print ("'%s' can mean multiple things. You can re-run your query "
"and add '-d #' where '#' is the topic number you're "
"interested in.\n" % q)
for i, related in enumerate(results.related[0:options.n]):
name = related.url.split("/")[-1].replace("_", " ")
summary = related.text
if len(summary) < len(related.text):
summary += "..."
print '%d. %s: %s\n' % (i + 1, name, summary)
else:
for i, result in enumerate(results.results[0:options.n]):
summary = result.text[0:70].replace(" ", " ")
if len(summary) < len(result.text):
summary += "..."
print "%d. %s" % (i + 1, summary)
print " <%s>\n" % result.url
if __name__ == '__main__':
main()