DuckDuckGo.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:DuckDuckGo-Python3-Library 作者: knight-shade 项目源码 文件源码
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.
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号