Manual:Pywikibot/Wikidata

From MediaWiki.org
Jump to: navigation, search

Other languages:
Deutsch • ‎English • ‎español • ‎suomi • ‎français • ‎italiano • ‎日本語 • ‎Lëtzebuergesch • ‎Nederlands • ‎polski • ‎português do Brasil

This page explains how to create python bots on Wikidata using the basic pywikibot library.

If you just want to run some scripts without writing a line of python, see the included Wikidata scripts.

Caution! Caution: The methods and results may be changed in the future, as Wikibase evolves.

Configuration[edit | edit source]

To start contributing/testing using your bot's account you must add the following to your user-config.py:

Production site
usernames['wikidata']['wikidata'] = u'YourBot'
Testing site
usernames['wikidata']['test'] = u'YourBot'

Working with pywikibot/core (former rewrite branch)[edit | edit source]

see d:Wikidata:Creating a bot for an extended documentation. pywikibot core supports most Wikibase features already, e.g., qualifiers, sources, properties with item, coordinate, time, and string type.

import pwb #only needed if you haven't installed the framework as side-package
import pywikibot
site = pywikibot.Site('en','wikipedia') #  any site will work, this is just an example
page = pywikibot.Page(site, 'Douglas Adams')
item = pywikibot.ItemPage.fromPage(page) #  this can be used for any page object
#you can also define an item like this
repo = site.data_repository()  # this is a DataSite object
item = pywikibot.ItemPage(repo, 'Q42')  # This will be functionally the same as the other item we defined
item.get() #  you need to call it to access any data.
sitelinks = item.sitelinks
aliases = item.aliases
if 'en' in item.labels:
    print 'The label in English is: ' + item.labels['en']
if item.claims:
    if 'P107' in item.claims:
        print item.claims['P107'][0].getTarget()
        print item.claims['P107'][0].sources[0] #  let's just assume it has sources.
 
# Edit an existing item
item.editLabels(labels={'language': 'en', 'value': 'Douglas Adams'}, summary=u'Edit label')
item.editDescriptions(descriptions={'language': 'en', 'value': 'English writer'}, summary=u'Edit description')
item.editAliases(aliases={'en':['An alias','Another alias']}, summary=u'Set aliases')
item.setSitelink(sitelink={'site': 'enwiki', 'title': 'Douglas Adams'}, summary=u'Set sitelink')
item.removeSitelink(site='enwiki', summary=u'Remove sitelink')
 
#You can also made this all in one time:
data = {'labels': {'language': 'en', 'value': 'Douglas Adams'},
  'descriptions': {'language': 'en', 'value': 'English writer'},
     'sitelinks': [{'site': 'enwiki', 'title': 'Douglas Adams'}]}
item.editEntity(data, summary=u'Edit item')

Working with pywikibot/compat (former trunk release)[edit | edit source]

See also[edit | edit source]