Python SPARQLWrapper指定URI无结果问题排查
SPARQL查询无结果的问题解决
你的Python代码无法返回结果的核心原因是查询字符串错误使用了HTML实体<和>,而非SPARQL语法要求的原生尖括号<和>。
在SPARQL网页界面中,输入框会自动处理HTML转义逻辑,你输入的<https://music.wikibase.cloud/prop/direct/P2>会被正确解析为URI;但在Python代码里,直接写入<和>会被SPARQL端点当作普通字符处理,等同于查询谓词为<https://music.wikibase.cloud/prop/direct/P2>的三元组,自然匹配不到数据。
修正后的代码如下:
from SPARQLWrapper import SPARQLWrapper, JSON import sys def get_results(endpoint_url, query): user_agent = "WDQS-example Python/%s.%s" % (sys.version_info[0], sys.version_info[1]) sparql = SPARQLWrapper(endpoint_url, agent=user_agent) sparql.setQuery(query) sparql.setReturnFormat(JSON) return sparql.query().convert() endpoint='https://music.wikibase.cloud/query/sparql' # 使用原生尖括号包裹URI,而非HTML实体 query="""construct where {?s <https://music.wikibase.cloud/prop/direct/P2> ?o.}""" get_results(endpoint,query)
你也可以通过打印query变量的内容,对比网页中实际执行的查询语句,就能直观看到二者的差异。
内容的提问来源于stack exchange,提问作者Michel
相关产品推荐
相关产品推荐

