Вікідані:Створення бота
Ця сторінка пояснює як створювати ботів для Вікіданих. Будь ласка, розгляньте можливість надання свого коду, додайте нові приклади та будь-які вдосконалення, які ви хочете.
Вимоги
Для створення ботів вам потрібні:
- Деякі навички кодування (Python, Perl, PHP, ...)
- Фреймворк (один із фреймворків нижче) та деякий код для запуску виконання завдання
- Обліковий запис бота (і затверджений)
- Редактор вихідного коду (Notepad++, Geany, vim, emacs)
Рекомендація
- Join a Wikidata telegram channel and participate in the discussions (and ask for help if you get stuck programming).
Pywikibot
Попередження: This bot framework has incomplete support of lexemes as of June 2022. See other libraries below for full support. |
У наступних розділах ви дізнаєтесь, як встановити, налаштувати та ввійти за допомогою pywikibot. Ці перші три кроки потрібно зробити лише один раз. Крім того, є кілька основних прикладів для вивчення основ програмування ботів.
Встановлення
- Детальніше про встановлення pywikibot див. mw:Manual:Pywikibot/Installation та Wikidata:Pywikibot - Python 3 Tutorial/Setting up Shop
- Щоб використовувати pywikibot без встановленя, див. mw:Manual:Pywikibot/PAWS
Щоб встановити pywikibot:
- Встановити Python (потрібен Python v3.5.2 або вище)
- Завантажити pywikibot:
- Як zip файл
- Або за допомогою репозиторію git: Manual:Pywikibot/Gerrit
Конфігурація
- Детальніше про конфігурацію pywikibot див. mw:Manual:Pywikibot/user-config.py.
Ви повинні налаштувати файл user-config.py
на ім'я користувача бота, потрібний проєкт та мову. Для Вікіданих параметри проєкту та мови однакові, wikidata
.
Extended content |
---|
mylang = "wikidata"
family = "wikidata"
usernames["wikidata"]["wikidata"] = 'MyBotName'
|
Ви можете зменшити затримку між редагуваннями, додавши: put_throttle = 1
Вхід до системи
Після налаштування файлу user-config.py
увійдіть так:
$ python login.py
У вас запитають пароль вашого бота — введіть його та натисніть Enter. Ви увійдете негайно.
Приклад 1: Отримати дані
Цей приклад отримує дані сторінки, що стосується Дугласа Адамса. Збережіть наступний вихідний код у файлі та виконайте його за допомогою python example1.py
Extended content |
---|
import pywikibot
site = pywikibot.Site("en", "wikipedia")
page = pywikibot.Page(site, 'Douglas Adams')
item = pywikibot.ItemPage.fromPage(page)
dictionary = item.get()
print(dictionary)
print(dictionary.keys())
print(item)
|
item.get()
під'єднується до Вікіданих та отримує дані. Отримані дані (переформатовані для зручності):
{ 'claims': { 'P646': [<pywikibot.page.Claim instance at 0x7f1880188b48>], 'P800': [<pywikibot.page.Claim instance at 0x7f1880188488>, <pywikibot.page.Claim instance at 0x7f1880188368>] ... } 'labels': { 'gu': '\u0aa1\u0a97\u0acd\u0ab2\u0abe\u0ab8 \u0a8f\u0aa1\u0aae\u0acd\u0ab8', 'scn': 'Douglas Adams', ... } 'sitelinks': { 'fiwiki': 'Douglas Adams', 'fawiki': '\u062f\u0627\u06af\u0644\u0627\u0633 \u0622\u062f\u0627\u0645\u0632', 'elwikiquote': '\u039d\u03c4\u03ac\u03b3\u03ba\u03bb\u03b1\u03c2 \u0386\u03bd\u03c4\u03b1\u03bc\u03c2', ... } 'descriptions': { 'eo': 'angla a\u016dtoro de sciencfikcio-romanoj kaj humoristo', 'en': 'English writer and humorist', }, 'aliases': { 'ru': ['\u0410\u0434\u0430\u043c\u0441, \u0414\u0443\u0433\u043b\u0430\u0441'], 'fr': ['Douglas Noel Adams', 'Douglas No\xebl Adams'], ... } } ['claims', 'labels', 'sitelinks', 'descriptions', 'aliases'] [[wikidata:Q42]]
Друкується словник з ключами для
- набору записів на сторінці: Property:P646 — ідентифікатор Freebase, Property:P800 — «визначний твір» тощо.
- назви елемента багатьма мовами
- посилання на сайт для даного елемента, не лише Вікіпедії багатьма мовами, але й Вікіцитати багатьма мовами
- опису елемента багатьма мовами
- псевдонімів елемента багатьма мовами
Потім список із усіма ключами для пар ключ-значення у словнику. Нарешті, ви бачите, що елемент Вікіданих про Дугласа Адамса — Q42.
Альтернативи
Наведений вище приклад отримує ItemPage за допомогою статті англійської Вікіпедії. Крім того, ми також можемо отримати ItemPage безпосередньо:
Extended content |
---|
import pywikibot
site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()
item = pywikibot.ItemPage(repo, 'Q42')
|
Приклад 2: Отримати інтервікі посилання
Наприклад, після item.get() можна отримати посилання на сайт. Це посилання на всі Вікіпедії, в яких є стаття.
Extended content |
---|
import pywikibot
site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()
item = pywikibot.ItemPage(repo, 'Q42')
item.get()
print(",".join(item.sitelinks))
|
Результат:
{'fiwiki': 'Douglas Adams', 'eowiki': 'Douglas Adams', 'dewiki': 'Douglas Adams', ...}
За допомогою item.iterlinks() повертається ітератор над усіма цими посиланнями на сайти, де кожна стаття подається не як звичайний текст, як зазначено вище, а вже як об’єкт Page для подальшої обробки (наприклад, редагування тексту у відповідних статтях Вікіпедії).
Приклад 4: Вказати опис
У цьому прикладі наведено опис англійською та німецькою мовами для статті про Дугласа Адамса.
Extended content |
---|
import pywikibot
site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()
item = pywikibot.ItemPage(repo, 'Q42')
item.get()
mydescriptions = {'en': 'English writer and humorist', 'de': 'Keine Panik!'}
item.editDescriptions(mydescriptions, summary='Setting/updating descriptions.')
|
Встановлення назв (labels) та псевдонімів працює відповідно.
Приклад 6: Вказати посилання на сайт
Щоб вказати посилання на сайт, ми можемо або створити відповідний словник (dict), що відповідає прикладу 4, або використати об’єкти Page:
Extended content |
---|
import pywikibot
site = pywikibot.Site("en", "wikipedia")
repo = site.data_repository()
item = pywikibot.ItemPage(repo, 'Q42')
page = pywikibot.Page(site, 'Douglas Adams')
item.setSitelink(page, summary='Setting (/updating?) sitelink.')
|
Приклад 7: Вказати твердження
Твердження задаються за допомогою класу Claim. Нижче ми задали для Дугласа Адамса place of birth (P19): Cambridge (Q350).
Extended content |
---|
import pywikibot
site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()
item = pywikibot.ItemPage(repo, 'Q42')
claim = pywikibot.Claim(repo, 'P19')
target = pywikibot.ItemPage(repo, 'Q350')
claim.setTarget(target)
item.addClaim(claim, summary='Adding claim')
|
Для інших типів даних це робиться аналогічно. Нижче ми додаємо твердження з рядковими (IMDb ID (P345)) та координатними (coordinate location (P625)) типами даних (URL-адреса така сама, як рядок):
Extended content |
---|
import pywikibot
site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()
item = pywikibot.ItemPage(repo, 'Q42')
stringclaim = pywikibot.Claim(repo, 'P345')
stringclaim.setTarget('nm0010930')
item.addClaim(stringclaim, summary='Adding string claim')
coordinateclaim = pywikibot.Claim(repo, 'P625')
coordinate = pywikibot.Coordinate(lat=52.208, lon=0.1225, precision=0.001, site=site)
coordinateclaim.setTarget(coordinate)
item.addClaim(coordinateclaim, summary='Adding coordinate claim')
|
Приклад 8: Додати кваліфікатор
Qualifiers are also represented by the Claim class. In the following, we add the qualifier incertae sedis (P678): family (Q35409) to the Claim "claim". Make sure you add the item before adding the qualifier.
Extended content |
---|
qualifier = pywikibot.Claim(repo, 'P678')
target = pywikibot.ItemPage(repo, "Q35409")
qualifier.setTarget(target)
claim.addQualifier(qualifier, summary='Adding a qualifier.')
|
Приклад 9: Додати джерело
Also, sources are represented by the Claim class. Unlike for qualifiers, a source may contain more than one Claim. In the following, we add stated in (P248): Integrated Taxonomic Information System (Q82575) with retrieved (P813) March 20, 2014 as source to the Claim "claim". The claim has to be either retrieved from Wikidata or added to an itempage beforehand.
Extended content |
---|
statedin = pywikibot.Claim(repo, 'P248')
itis = pywikibot.ItemPage(repo, "Q82575")
statedin.setTarget(itis)
retrieved = pywikibot.Claim(repo, 'P813')
date = pywikibot.WbTime(year=2014, month=3, day=20)
retrieved.setTarget(date)
claim.addSources([statedin, retrieved], summary='Adding sources.')
|
Приклад 10: Генератори сторінок
TODO
Приклад 11: Отримати значення підвластивостей
In the following, we get values of sub-properties from branch described by source (P1343) -> Great Soviet Encyclopedia (1969–1978) (Q17378135) -> properties reference URL (P854) and title (P1476).
Extended content |
---|
import pywikibot
site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()
item = pywikibot.ItemPage(repo, 'Q13515')
item.get()
sourcesid = 'P1343'
sourceid = 'Q17378135'
urlid = 'P854'
nameid = 'P1476'
# item.claims['P1343'][1].qualifiers.items(): # This are direct way to get list qualifiers. But '[1]' is hard link to index of list, it will break over time.
if sourcesid in item.claims:
for source in item.claims[sourcesid]:
if source.target.id == sourceid:
s = source.qualifiers
if urlid in s: url = s.get(urlid)[0].target
if nameid in s: name = s.get(nameid)[0].target['text']
print (url, name)
|
Більше прикладів
Деякі користувачі діляться своїми джерельними кодами. Дізнайтеся більше за такими посиланнями:
- User:RobotMichiel1972/wikidata lowercase.py — приклад pywikipedia, як ви можете виправити назву (label) на нижній регістр, використовуючи розмір літер назви (label) англійською мовою як „посилання” (тут жорстко закодовано, реалізовано лише для nlwiki), переглядаючи вибір сторінок у власній Вікіпедії.
- File:Bots hackathon 2013.pdf, що представляє "claimit.py" та "template_harvest.py", включені до основної версії (колишня переписана).
Інтегратор Вікіданих
WikidataIntegrator — це бібліотека для читання та запису на Вікіданих/Wikibase. Ми створили його для заповнення Вікіданих вмістом із авторитетних ресурсів про гени, білки, хвороби, ліки та інше. Подробиці різних завдань можна знайти на сторінці Вікіданих бота.
Pywikibot — це існуюча платформа для взаємодії з API MediaWiki. Причина, по якій ми придумали власне рішення, полягає в тому, що нам потрібна висока інтеграція з точкою доступу Wikidata SPARQL, щоб забезпечити узгодженість даних (перевірки дублікатів, перевірка узгодженості, правильний вибір елементів тощо). Порівняно з Pywikibot, WikidataIntegrator тепер не є повною обгорткою Python для API MediaWiki, а зосереджена виключно на забезпеченні простих засобів для створення ботів на основі Вікіданих на основі Python.
Для отримання додаткової інформації, документації, інструкцій із завантаження та встановлення, див. тут: https://github.com/SuLab/WikidataIntegrator/
Example Notebook
An example notebook demonstrating an example bot to add therapeutic areas to drug items, including using fastrun mode, checking references, and removing old statements:
http://public-paws.wmcloud.org/46883698/example%20ema%20bot.ipynb
WikibaseIntegrator
Forked from Wikidata Integrator by User:Myst in 2020 and has seen several improvements to the API that makes it even easier to create bots using the library.
For more information, documentation, download & installation instructions, see here: https://github.com/LeMyst/WikibaseIntegrator
Example semi-automatic script
LexUse semi-automatic tool for finding and adding usage examples to lexemes. It's free software written using Python 3 in 2020 Wikidata:LexUse.
Wikibase.NET (Застаріле)
Wikibase.NET is the api that replaces the now deprecated DotNetDataBot. Api client for the MediaWiki extension Wikibase. They aren't compatible because Wikibase.NET does no longer need the DotNetWikiBot framework.
Завантаження і встановлення
You can download Wikibase.NET from GitHub. Just follow the instructions on that page.
Відомі проблеми
Приклади
Coming not soon...
DotNetDataBot (Застаріле)
Встановлення
- Download: DotNetDataBot
Конфігурація
After unpacking the package you can see a file called DotNetDataBot.dll and one called DotNetDataBot.xml. The xml document is only for documentation. To use it you have to create a new refer in your project. Then you can write using DotNetDataBot;
to import the framework.
Вхід до системи
To login you have to create a new Site
object with the url of the wiki, your bot's username and its password.
Extended content |
---|
C# using DotNetDataBot;
public static void Main()
{
Site wikidata = new Site("http://www.wikidata.org", "User", "Password");
}
|
Example 1: Get id using wiki page
You can access the id of an item by searching for using the site and the title of the connected page.
Extended content |
---|
C# using DotNetDataBot;
public static void Main()
{
Site site = new Site("http://www.wikidata.org", "User", "Password");
Item item = new Item(site);
if (item.itemExists("it", "George Lucas")) // Check if exist on Wikidata
{
Console.Write("Q" + item.GetIdBySitelink("it", "George Lucas"));
}
else
{
Console.Write("Doesn't exist");
}
}
|
Example 2: Get interwiki links
You can get the interwiki links of an item by loading the content and accessing the links
field of the object.
Extended content |
---|
C# using DotNetDataBot;
public static void Main()
{
Site site = new Site("http://www.wikidata.org", "User", "Password");
Item item = new Item(site);
item.id = item.GetIdBySitelink("it", "George Lucas");
item.Load();
foreach(KeyValuePair<string, string> link in item.links)
{
Console.Write(link.Key); // lang (eg. en or it)
Console.Write(link.Value); // page (eg. George_Lucas)
}
}
|
Example 3: Set a description
To set a description, you must call the setDescription
function.
Extended content |
---|
C# using DotNetDataBot;
public static void Main()
{
Site site = new Site("http://www.wikidata.org", "User", "Password");
Item item = new Item(site, "Q4115189");
item.Load();
if (item.descriptions.ContainsKey("it")) // if alredy exist description in italian
{
// Nothing to do
}
else
{
item.setDescription("it", "description in italian", "Bot: Add italian description");
}
}
|
Example 4: Set a label
It works the same way for setting a label. Just call setLabel
.
Extended content |
---|
C# using DotNetDataBot;
public static void Main()
{
Site site = new Site("http://www.wikidata.org", "User", "Password");
Item item = new Item(site, "Q4115189");
item.Load();
if (item.labels.ContainsKey("it")) // if alredy exist label in italian
{
// Nothing to do
}
else
{
item.setLabel("it", "label in italian", "Bot: Add italian label");
}
}
|
Example 5: Get interwiki links for 100 pages
This feature is not supported. Just iterate over the list.
Wikibase api для PHP
Це api-клієнт для Wikibase, написаний на PHP. Його можна завантажити тут.
Приклад 1: Основний приклад
Take a look at the source comments to understand how it works.
Extended content |
---|
<?php
/**
* Basic example for the use of the libary with some small edits
*/
require_once( __DIR__ . "/vendor/autoload.php" );
// Creates some useful objects and logs into the api
$api = new \Mediawiki\Api\MediawikiApi( "http://www.wikidata.org/w/api.php" );
$api->login( new \Mediawiki\Api\ApiUser( 'username', 'password' ) );
$dataValueClasses = array(
'unknown' => 'DataValues\UnknownValue',
'string' => 'DataValues\StringValue',
);
$wikidata = new \Wikibase\Api\WikibaseFactory(
$api,
new DataValues\Deserializers\DataValueDeserializer( $dataValueClasses ),
new DataValues\Serializers\DataValueSerializer()
);
// Gets the current revision for item Q777
$revision = $wikidata->newRevisionGetter()->getFromId( 'Q777' );
$item = $revision->getContent()->getData();
// Outputs the current sitelink for enwiki
var_dump( $item->getSiteLink( 'enwiki' ) );
// Sets the de description to 'Foobar'
$item->getFingerprint()->setDescription( 'de', 'Foobar' );
// Saves the item
$wikidata->newRevisionSaver()->save( $revision );
//Log out
$api->logout();
|
Приклад 2: Створення записів
Take a look at the source comments to understand how it works.
Extended content |
---|
<?php
/**
* Basic example for the use of the library with some small edits.
*/
require_once( __DIR__ . "/vendor/autoload.php" );
// Creates some useful objects and logs into the api
$api = new \Mediawiki\Api\MediawikiApi( "https://www.wikidata.org/w/api.php" );
$api->login( new \Mediawiki\Api\ApiUser( 'username', 'password' ) );
$dataValueClasses = array(
'unknown' => 'DataValues\UnknownValue',
'string' => 'DataValues\StringValue',
);
$services = new \Wikibase\Api\WikibaseFactory(
$api,
new DataValues\Deserializers\DataValueDeserializer( $dataValueClasses ),
new DataValues\Serializers\DataValueSerializer()
);
$revision = $services->newRevisionGetter()->getFromId( 'Q777' );
$item = $revision->getContent()->getData();
$statementList = $item->getStatements();
if( $statementList->getByPropertyId( \Wikibase\DataModel\Entity\PropertyId::newFromNumber( 1320 ) )->isEmpty() ) {
$services->newStatementCreator()->create(
new \Wikibase\DataModel\Snak\PropertyValueSnak(
\Wikibase\DataModel\Entity\PropertyId::newFromNumber( 1320 ),
new \DataValues\StringValue( 'New String Value' )
),
'Q777'
);
}
// Log out
$api->logout();
|
VBot (no updates since 2017)
Framework for Wikidata and Wikipedia. Read and write on Wikidata and other Wikimedia project and have a useful list generator to generate list of Wikipedia page and Wikidata entity. Can read also JSON dump of Wikidata.
Огляд
Bot to read and edit Wikidata and Wikipedia.
- License: CC0 1.0
- Language C#
- Can read and write entities with all datatype on Wikidata
- Can read and write pages on all Wiki project
- Can read parameter from template on wiki pages
- Can read JSON dump
- Can create lists using:
- Wikidata query
- Catscan 2
- Quick intersection
- What Links Here on Wikidata
- Tested with Visual Studio Express 2013 for Windows Desktop.
- Is necessary to have Newtonsoft.Json. You can install it with NuGet inside Visual Studio
- Is necessary to add manually a reference to System.Web for "HttpUtility.UrlEncode"
Завантаження
The framework can be downloaded from GitHub here.
Інструкція
- Wiki (часткова)
- User talk:ValterVB :)
Приклад 1
Update en label for all items with instance of (P31): short film (Q24862) that have director (P57) and that have publication date (P577) in 1908. (Use of Wikidata query)
Extended content |
---|
private void CompleteExample()
{
//Wikidata query
string strWDQ = "CLAIM[31:24862] AND CLAIM[57] AND BETWEEN[577,+00000001908-00-00T00:00:00Z,+00000001908-12-31T00:00:00Z]";
ListGenerator lg = new ListGenerator();
List<string> chunks = lg.WDQ(strWDQ, 50);
//Connection to Wikipedia
WikimediaAPI WP = new WikimediaAPI("https://it.wikipedia.org", User, Password);
Pages PageList = new Pages();
//Connection to Wikidata
WikimediaAPI WD = new WikimediaAPI("https://www.wikidata.org", User, Password);
Entities EntityList = new Entities();
Dictionary<string, string> Labels = new Dictionary<string, string>();
foreach (string list in chunks)
{
// Load all entity of the chunk
string strJson = WD.LoadWD(list);
EntityList = new Entities();
EntityList = JsonConvert.DeserializeObject<Entities>(strJson, new DatavalueConverter());
foreach (KeyValuePair<string, Entity> entity in EntityList.entities)
{
if (entity.Value.sitelinks.ContainsKey("itwiki"))
{
// Load Wikipage
string Pages = WP.LoadWP(entity.Value.sitelinks["itwiki"].title);
PageList = JsonConvert.DeserializeObject<Pages>(Pages, new DatavalueConverter());
//Director from template
string director = Utility.GetTemplateParameter(PageList.query.FirstPageText, "film","Regista").Replace("[","").Replace("]", "");
Labels = new Dictionary<string, string>();
if (director=="")
{
Labels.Add("en", "1908 short movie");
}
else
{
Labels.Add("en", "1908 short movie directed by " + director);
}
// Update Wikidata
WD.EditEntity(entity.Value.id, null, Labels, null, null, null, "BOT: Update en label");
}
}
}
}
|
LexData (Python; для Lexicographical data)
LexData — проста у використанні бібліотека python для створення та редагування лексем, сенсів та форм.
LexData is an easy to use python libary to create and edit Lexemes, Senses and Forms.
Поради
The documentation of LexData is still a bit lacking so look at existing implementations in MachtSinn or Wikdata Lexeme Forms for ideas how to use it.
If you only want to add statements to Lexemes (not forms or senses) WikibaseIntegrator might be a better choice, as it is more versatile and support a lot of data types.
Встановлення
Ви можете встановити LexData через pip:
You can install LexData via pip:
$ pip install LexData
Вхід у систему
Для всіх операцій вам потрібна WikidataSession
. Ви можете створити її за допомогою своїх облікових даних, пароля бота або токен редагування (наприклад, щоб редагувати через OAUTH):
For all operations you need a WikidataSession
. You can create it with your credentials, a bot password or an Edit Token (for example to edit via OAUTH):
Extended content |
---|
repo = LexData.WikidataSession("YourUsername", "YourPassword")
|
Отримати лексему
Ви можете відкрити існуючі Лексеми та прочитати їх вміст.
You can open existing Lexemes and read their content.
Extended content |
---|
L2 = LexData.Lexeme(repo, "L2")
print(L2.claims)
print(L2.forms)
print(L2.senses)
sense1 = L2.senses[0]
print(sense1.claims)
|
Пошук і створення лексем
Якщо ви не знаєте L-ідентифікатор лексеми, можете шукати її. А якщо її не існує, ви можете створити її.
If you don't know the L-Id of a lexeme you can search for it. And if it doesn't exist you can create it.
Extended content |
---|
# Find an existing Lexeme by lemma, language and grammatical form
L2 = LexData.search_lexemes(repo, "first", en, "Q1084")
# Create a new Lexeme
L2 = LexData.create_lexeme(repo, "first", en, "Q1084")
# Find or create a Lexeme
L2 = LexData.get_or_create_lexeme(repo, "first", en, "Q1084")
|
Додавання інформації
Ви можете легко створювати форми або сенси, з додатковими записами або без них:
You can easily create forms or senses, with or without additional claims:
Extended content |
---|
if len(L2.forms) == 0:
L2.createForm("firsts", ["Q146786"])
if len(L2.senses) == 0:
L2.createSense(
{
"en": "Element in an ordered list which comes before all others according to the ordering",
"de": "einer Ordnung folgend das Element vor allen anderen",
},
claims={"P5137": ["Q19269277"]},
)
|
Пряме використання API Вікіданих
В інших розділах описано, як використовувати фреймворки ботів для доступу та оновлення інформації Вікіданих.
Ви також можете безпосередньо взаємодіяти з API Wikibase, який надають Вікідані.
Це треба робити, якщо ви розробляєте власний фреймворк або якщо вам потрібно зробити щось, що фреймворк не підтримує.
Документацію щодо API Wikibase можна знайти за адресою mediawiki.org. Ви також можете з ним пограти на Special:ApiSandbox, спробуйте action=wbgetentities
.
Wikibase надає свій API як набір модулів для API "дій" MediaWiki. Ви отримуєте доступ до них, роблячи HTTP-запити на /w/api.php
.
Типовим форматом відповіді є JSON.
Отже, для обраної вами мови вам потрібна лише бібліотека для виконання запитів HTTP та бібліотека JSON або XML для синтаксичного аналізу відповідей.
Приклад 1: Отримати номер Q
Цей приклад отримує Q-номер елемента для статті в англійській Вікіпедії про Галактику Андромеди. Цю інформацію надає основний модуль "робочої конячки" API Wikibase action=wbgetentities
. Запитом HTTP (з використанням формату jsonfm
для зручного читання виводу JSON) є просто
Спробуйте перейти за посиланням. Це не вимагає додаткової інформації про сутність; видаліть &props=
з URL-адреси, щоб побачити набагато більше інформації про неї.
Докладніше про параметри, які ви можете вказати, див. згенеровану довідку щодо wbgetentities
.
Python
Extended content |
---|
#!/usr/bin/python3
from requests import get
def get_qnumber(wikiarticle, wikisite):
resp = get('https://www.wikidata.org/w/api.php', {
'action': 'wbgetentities',
'titles': wikiarticle,
'sites': wikisite,
'props': '',
'format': 'json'
}).json()
return list(resp['entities'])[0]
print(get_qnumber(wikiarticle="Andromeda Galaxy", wikisite="enwiki"))
|
Результат:
Q2469
Приклад 2: Отримати список елементів без певних інтервік
...будь ласка, додайте, якщо знаєте як...
...please contribute if you know how...
Див. також
- mw:Wikidata Toolkit Java framework
- Wikidata:Bots
- Боти Вікіданих за функціональністю
- Посібник Pywikibot - Python 3 на Вікіданих
- Пісочниця Вікіданих