如何获取Wikidata各类实体ID?是否有适配Python的可用API?
获取Wikidata各类实体ID的通用方法(含Python实现)
问题分析
你之前用MediaWiki API查询属性(Property)时得到错误结果,核心原因是默认查询的是主命名空间(ns=0)的Item页面,而Wikidata的Property实体属于命名空间120,Lexeme属于命名空间146。要实现通用查询,要么调整请求参数匹配对应命名空间,要么用专门针对Wikidata实体设计的搜索接口。
通用API查询方法
1. 使用wbsearchentities接口(推荐)
这个接口是Wikidata专门提供的实体搜索工具,支持直接指定实体类型(Item/Property/Lexeme),返回结果精准匹配需求。
查询Property示例(以"developer"为例)
/w/api.php?action=wbsearchentities&format=json&search=developer&language=en&type=property&formatversion=2
返回结果里会直接给出id: "P178",就是你需要的属性ID。
查询所有类型实体
如果不指定type参数,会返回所有匹配的实体类型:
/w/api.php?action=wbsearchentities&format=json&search=skype&language=en&formatversion=2
这会同时列出Item(Q40984)、相关Property等匹配结果。
2. 调整命名空间参数(兼容原query接口)
如果坚持用你之前的query接口,只需在请求中指定对应命名空间:
- Item对应
ns=0 - Property对应
ns=120 - Lexeme对应
ns=146
查询"developer"属性的请求示例:
/w/api.php?action=query&format=json&prop=pageprops&titles=developer&formatversion=2&ppprop=wikibase_item&ns=120
返回结果中的wikibase_item字段就是P178。
Python实现方案
1. 轻量方案:直接用requests调用API
不需要额外依赖第三方库,灵活度高:
import requests def get_wikidata_entity_id(search_term, entity_type=None, language="en"): api_url = "https://www.wikidata.org/w/api.php" params = { "action": "wbsearchentities", "format": "json", "search": search_term, "language": language, "formatversion": 2 } if entity_type: params["type"] = entity_type response = requests.get(api_url, params=params) data = response.json() if data.get("search"): # 返回第一个匹配结果的ID return data["search"][0]["id"] return None # 调用示例 print(get_wikidata_entity_id("developer", entity_type="property")) # 输出 P178 print(get_wikidata_entity_id("skype", entity_type="item")) # 输出 Q40984 print(get_wikidata_entity_id("skype")) # 输出第一个匹配的实体ID
2. 专用库方案:使用WikidataIntegrator
这是专门为Wikidata开发的Python库,封装了大量常用操作:
from wikidataintegrator import wdi_core def get_entity_id_with_wdi(search_term, entity_type=None): search_results = wdi_core.WDItemEngine.get_wd_search_results(search_term, language="en") if not search_results: return None # 按实体类型过滤结果 if entity_type: filtered_results = [res for res in search_results if res["entity-type"] == entity_type] return filtered_results[0]["id"] if filtered_results else None return search_results[0]["id"] # 调用示例 print(get_entity_id_with_wdi("developer", "property")) # 输出 P178
3. 全功能方案:使用pywikibot
MediaWiki官方推荐的Python库,适合复杂的Wikidata操作场景:
import pywikibot def get_entity_id_with_pywikibot(search_term, entity_type=None): site = pywikibot.Site("wikidata", "wikidata") repo = site.data_repository() # 搜索匹配的实体 for result in repo.search(search_term, language="en"): if not entity_type or result.entity_type == entity_type: return result.id return None # 调用示例 print(get_entity_id_with_pywikibot("developer", "property")) # 输出 P178
总结
- 优先选择
wbsearchentities接口,它是专门为Wikidata实体搜索设计的,无需手动处理命名空间,适配所有实体类型。 - Python实现上,轻量需求用
requests即可,复杂操作可以选择WikidataIntegrator或pywikibot,后者还支持编辑、批量操作等进阶功能。
内容的提问来源于stack exchange,提问作者Xue Li
相关产品推荐
相关产品推荐

