forked from mikejs/python-duckduckgo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ddg3.py
208 lines (167 loc) · 5.79 KB
/
ddg3.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python3
"""
duck duck go module for python 3
"""
import urllib.parse
import requests
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from typing import Optional
__version__ = "VERSION"
__useragent__ = "ddg3 {__version__}"
class Results:
"""ddg results object"""
def __init__(self, xml: Element) -> None:
"""constructor"""
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.answer: Optional[Answer] = None
self.image: Optional[Image] = None
try:
self.results = [Result(elem) for elem in xml.getiterator("Result")] # type: ignore
self.related = [
Result(elem) for elem in xml.getiterator("RelatedTopic") # type: ignore
]
except AttributeError:
self.results = [Result(elem) for elem in xml.iter("Result")]
self.related = [Result(elem) for elem in xml.iter("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:
"""ddg abstract object"""
def __init__(self, xml: Element) -> None:
"""constructor"""
self.html = xml.findtext("Abstract", "")
self.text = xml.findtext("AbstractText", "")
self.url = xml.findtext("AbstractURL", "")
self.source = xml.findtext("AbstractSource")
class Result:
"""ddg result object"""
def __init__(self, xml: Element) -> None:
"""constructor"""
self.html = xml.text
self.text = xml.findtext("Text")
self.url = xml.findtext("FirstURL")
self.icon: Optional[Image] = None
icon_xml = xml.find("Icon")
if icon_xml is not None:
self.icon = Image(icon_xml)
else:
self.icon = None
class Image:
"""ddg image object"""
def __init__(self, xml: Element) -> None:
"""constructor"""
self.url = xml.text
self.height = xml.attrib.get("height", None)
self.width = xml.attrib.get("width", None)
class Answer:
"""ddg answer object"""
def __init__(self, xml: Element) -> None:
"""constructor"""
self.text = xml.text
self.type = xml.attrib.get("type", "")
def query(query_text: str, useragent: str = __useragent__) -> Results:
"""
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.parse.urlencode({"q": query_text, "o": "x"})
url = f"http://api.duckduckgo.com/?{params}"
request = requests.get(url, headers={"User-Agent": useragent})
response = request.text
xml = ElementTree.fromstring(response)
return Results(xml)
def main() -> None:
"""main function for when run as a cli tool"""
import sys
from optparse import OptionParser
parser = OptionParser(
usage="usage: %prog [options] query", version=f"ddg3 {__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 webbrowser
query_url = urllib.parse.urlencode(dict(q=q))
webbrowser.open(f"http://duckduckgo.com/?{query_url}", 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(f"Answer: {results.answer.text}\n")
elif results.abstract and results.abstract.text:
print(f"{results.abstract.text}\n")
if results.type == "disambiguation":
print(
f"""
'{q}' can mean multiple things. You can re-run your query
and add '-d #' where '#' is the topic number you're
interested in.
""".replace(
"\n", ""
).replace(
"\t", " "
)
)
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(f"{i+1}. {name}: {summary}\n")
else:
for i, result in enumerate(results.results[0 : options.n]):
if result.text:
summary = result.text[0:70].replace(" ", " ")
if len(summary) < len(result.text):
summary += "..."
print(f"{i + 1}. {summary}")
print(f" <{result.url}>\n")
if __name__ == "__main__":
main()