diff --git a/duckduckgo.py b/duckduckgo.py index 4f81e06..5a50298 100755 --- a/duckduckgo.py +++ b/duckduckgo.py @@ -5,8 +5,15 @@ # # See LICENSE for terms of usage, modification and redistribution. -import urllib -import urllib2 +try: + import urllib.parse as urllib +except ImportError: + import urllib +try: + import urllib.request as urllib2 +except ImportError: + import urllib2 + import json as j import sys @@ -52,7 +59,7 @@ def query(query, useragent='python-duckduckgo '+str(__version__), safesearch=Tru request = urllib2.Request(url, headers={'User-Agent': useragent}) response = urllib2.urlopen(request) - json = j.loads(response.read()) + json = j.loads(response.read().decode('utf-8')) response.close() return Results(json) @@ -138,7 +145,7 @@ def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', ' '''A helper method to get a single (and hopefully the best) ZCI result. priority=list can be used to set the order in which fields will be checked for answers. Use web_fallback=True to fall back to grabbing the first web result. - passed to query. This method will fall back to 'Sorry, no results.' + passed to query. This method will fall back to 'Sorry, no results.' if it cannot find anything.''' ddg = query('\\'+q, **kwargs) @@ -150,13 +157,13 @@ def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', ' index = int(ps[1]) if len(ps) > 1 else None result = getattr(ddg, type) - if index is not None: + if index is not None: if not hasattr(result, '__getitem__'): raise TypeError('%s field is not indexable' % type) result = result[index] if len(result) > index else None if not result: continue if result.text: response = result.text - if result.text and hasattr(result,'url') and urls: + if result.text and hasattr(result,'url') and urls: if result.url: response += ' (%s)' % result.url if response: break @@ -166,7 +173,7 @@ def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', ' response = ddg.redirect.url # final fallback - if not response: + if not response: response = 'Sorry, no results.' return response @@ -179,7 +186,7 @@ def main(): for key in keys: sys.stdout.write(key) if type(q.json[key]) in [str,unicode,int]: print(':', q.json[key]) - else: + else: sys.stdout.write('\n') for i in q.json[key]: print('\t',i) else: