def search(query, web = False, useragent = "DuckDuckGo Python3 Api", skip_disambig = True, pretty = True, **kwargs):
'''
Searching the DuckDuckGo search engine and returning a Result object.
Keyworld Arguments:
query : Straightforward, the search string.
web : If true, opens the web browser and skips and command line. Default: False
useragent : Useragent to use while searching. Default: "DuckDuckGo Python3 Api". Can be overridden.
skip_disambig : Used to skip disambiguation. Default: 1 (True)
pretty : To make JSON look pretty. Default: 1 (True)
**kwargs : Any other parameters passed. As of writing this API no other parameters exists, helpful for future scaling.
'''
parameters = {'q': query, 'format': 'json', 'pretty': pretty, 'no_redirect': 1, 'no_html': 1, 'skip_disambig': skip_disambig}
encoded_parameters = urllib.parse.urlencode(parameters)
url = 'http://api.duckduckgo.com/?' + encoded_parameters
# Performs the Web browser search instead of instant answer API.
if web:
url = 'http://duckduckgo.com/?ia=web&' + urllib.parse.urlencode({'q': query})
webbrowser.open(url)
return
request = urllib.request.Request(url, headers = {'User-Agent': useragent})
try:
response = urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
print("The server couldn't fulfill the request.")
print("Error code: {}, Response: {}.".format(e.code, http.HTTPStatus(e.code)))
except urllib.error.URLError as e:
print("We failed to reach the server.")
print("Reason: {}", e.reason)
else:
response = response.read().decode()
response = json.loads(response)
return Result(response)
# Below are the return fields as class objects.
DuckDuckGo.py 文件源码
python
阅读 22
收藏 0
点赞 0
评论 0
评论列表
文章目录