首页 > 解决方案 > DuckDuckGo API 在编码的 url 查询中有空格时没有响应

问题描述

我有两个真正的问题。两者都与此代码有关:

import urllib
import requests

def query(q):
    base_url = "https://api.duckduckgo.com/?q={}&format=json"
    resp = requests.get(base_url.format(urllib.parse.quote(q)))
    json = resp.json()
    return json

一个是这样的:当我查询这样的内容时:“美国总统”,我得到这样的结果:

{'Abstract': '', 'AbstractSource': '', 'AbstractText': '', 'AbstractURL': '', 'Answer': '', 'AnswerType': '', 'Definition': '', 'DefinitionSource': '', 'DefinitionURL': '', 'Entity': '', 'Heading': '', 'Image': '', 'ImageHeight': '', 'ImageIsLogo': '', 'ImageWidth': '', 'Infobox': '', 'Redirect': '', 'RelatedTopics': [], 'Results': [], 'Type': '', 'meta': {'attribution': None, 'blockgroup': None, 'created_date': '2021-03-24', 'description': 'testing', 'designer': None, 'dev_date': '2021-03-24', 'dev_milestone': 'development', 'developer': [{'name': 'zt', 'type': 'duck.co', 'url': 'https://duck.co/user/zt'}], 'example_query': '', 'id': 'just_another_test', 'is_stackexchange': 0, 'js_callback_name': 'another_test', 'live_date': None, 'maintainer': {'github': ''}, 'name': 'Just Another Test', 'perl_module': 'DDG::Lontail::AnotherTest', 'producer': None, 'production_state': 'offline', 'repo': 'fathead', 'signal_from': 'just_another_test', 'src_domain': 'how about there', 'src_id': None, 'src_name': 'hi there', 'src_options': {'directory': '', 'is_fanon': 0, 'is_mediawiki': 0, 'is_wikipedia': 0, 'language': '', 'min_abstract_length': None, 'skip_abstract': 0, 'skip_abstract_paren': 0, 'skip_icon': 0, 'skip_image_name': 0, 'skip_qr': '', 'src_info': '', 'src_skip': ''}, 'src_url': 'Hello there', 'status': None, 'tab': 'is this source', 'topic': [], 'unsafe': None}}

基本上,一切都是空的。甚至我知道的标题键也是以“美国总统”的形式发送的,编码为 url 形式。这个问题似乎会影响我发送的所有带有空格的查询。即使我在浏览器中访问此网址:“https://api.duckduckgo.com/?q=US%20Presidents&format=json&pretty=1”,我得到的只是一堆空白的 json 键。

我的下一个问题是这个。当我发送这样的内容时:“1+1”,json 响应的“Answer”键是这样的:

{'from': 'calculator', 'id': 'calculator', 'name': 'Calculator', 'result': '', 'signal': 'high', 'templates': {'group': 'base', 'options': {'content': 'DDH.calculator.content'}}}

其他一切似乎都是正确的,但“结果”应该是“2”,不是吗?整个 json 的其余部分似乎是正确的,包括所有“RelatedTopics”

对此的任何帮助将不胜感激。

标签: pythonduckduckgo

解决方案


基本上duckduckgo api不是一个真正的搜索引擎。它只是一本字典。所以尝试US%20President代替,US%20presidents你会得到答案。对于编码,您可以使用空格,但如果它不是一个固定术语,我更喜欢加号。您可以使用urllib.parse.quote_plus()

通过计算,你是对的。但我绝对看不到在 python 代码中使用 calculus-api 的用例。如果有火箭可用,这就像使用蹦床去月球旅行。也许他们也有同样的看法,并且不在他们的 api 中提供计算服务?!


推荐阅读