pythonpython-3.xweb-scrapinggoogle-apiduckduckgo

How to get quick answers in Google or DuckDuckGo using Python


I have an AI Assistant project and I want it to search in internet. I want to use Google Quick Answer Box or DuckDuckGo Instant Answer API for Python. I saw other questions but they didn't help me so much. Here is an example what I want to achieve:

Question: What is giraffe?

Google's Answer:

enter image description here

DuckDuckGo's Answer:

enter image description here

As you can see the answers start with,

'The giraffe is an African artiodactyl mammal...'

How can I get this text using Python? (let me say 'what is giraffe' is an example. i want to use this method almost everything like 'tell me president of united states' etc.)


Solution

  • You can use duckduckgo API as suggested in the comments using :

    GET https://api.duckduckgo.com?q=[your query]&format=json
    

    Here is an example using :

    import requests
    
    query = "What is giraffe?"
    
    r = requests.get("https://api.duckduckgo.com",
        params = {
            "q": query,
            "format": "json"
        })
    
    data = r.json()
    
    print(data)
    
    print("Abstract")
    print(data["Abstract"])
    

    Output:

    The giraffe is an African artiodactyl mammal, the tallest living terrestrial animal and the largest ruminant. ..........