Pywikibot
Pywikibot is a Python library and framework for automating interactions with MediaWiki sites. It provides classes and functions to access, modify, and manage content programmatically, enabling developers to create bots for tasks like editing pages, managing categories, and extracting data. The current stable version is 11.1.0, and it follows a semi-regular release cadence, often aligning with MediaWiki updates.
Common errors
-
pywikibot.exceptions.LoginError: Login failed for user 'your_username'.
cause Incorrect credentials or site specified in `user-config.py`, `site.login()` not called, or Two-Factor Authentication/CAPTCHA awaiting input.fixEnsure `user-config.py` has correct `usernames`, `password` (or `password_file`), and `family` settings. Call `site.login()` after creating the `Site` object. Manually log in via browser for CAPTCHA/2FA if necessary, then try again. -
ImportError: cannot import name 'Site' from 'pywikibot.site'
cause Attempting to import internal components directly. `Site` and `Page` are exposed at the top level of `pywikibot` for convenience.fixUse `import pywikibot` and then access objects via `pywikibot.Site()` and `pywikibot.Page()`. -
pywikibot.exceptions.NoPageError: No page 'NonExistentPage' on site 'en:wikipedia'.
cause The specified page title does not exist on the target wiki, or there's a typo in the title.fixVerify the page title and confirm its existence on the wiki (case sensitivity matters for some wikis). -
TypeError: Page() got an unexpected keyword argument 'title'
cause Using an outdated `Page` constructor signature from an older major version of Pywikibot.fixConsult the latest documentation for `pywikibot.Page` constructor arguments. Typically, `pywikibot.Page(site_object, 'Page Title')` is the correct form.
Warnings
- gotcha Essential Configuration via `user-config.py`. Many basic operations, especially write actions, fail without proper configuration of your username, password, and default wiki site in `user-config.py`. This file is not automatically created and is critical for operation.
- gotcha Explicit Login Required. For most write operations (and even some read operations on private wikis), you must explicitly call `site.login()`. Forgetting this leads to permission errors or unexpected behavior.
- breaking Significant API Changes from v9.0.0 onwards. Pywikibot underwent a major rewrite, especially affecting how `Site` and `Page` objects are handled, method names, and return types. Scripts written for older versions (e.g., v8.x) will likely require substantial updates.
- gotcha MediaWiki API Rate Limits. Aggressive or poorly designed bots can quickly hit MediaWiki API rate limits, leading to temporary blocks from the wiki. While Pywikibot has internal throttling, it's not foolproof against rapid, high-volume requests.
- deprecated The `pywikibot.bot.Robot` class and related modules are deprecated. Developers are encouraged to use `pywikibot.Site`, `pywikibot.Page`, and other core Pywikibot objects directly.
Install
-
pip install pywikibot
Imports
- Site, Page
from pywikibot.site import Site
import pywikibot # then pywikibot.Site(), pywikibot.Page()
Quickstart
import pywikibot
import os
# --- Pywikibot requires a user-config.py file for site configuration and credentials ---
# Create a user-config.py in your bot's directory or the pywikibot installation directory.
# Example user-config.py content (replace with your actual info):
# family = 'wikipedia'
#mylang = 'en'
#usernames['wikipedia']['en'] = 'YourBotUsername'
#password_file = 'user-password.py' # or password['wikipedia']['en'] = 'YourBotPassword'
# Use 'en', 'wikipedia' for the English Wikipedia, or other codes for different sites.
site = pywikibot.Site(os.environ.get('PYWIKIBOT_LANG', 'en'), os.environ.get('PYWIKIBOT_FAMILY', 'wikipedia'))
try:
site.login() # Attempt to log in based on user-config.py
print(f"Successfully logged in to {site.family.name}:{site.lang} as {site.user().name}")
except pywikibot.exceptions.LoginError as e:
print(f"Login failed: {e}. Check user-config.py and ensure credentials are correct.")
# Fallback to anonymous for read-only actions if login isn't strictly needed
print("Proceeding with anonymous access for read-only operations.")
page = pywikibot.Page(site, os.environ.get('PYWIKIBOT_PAGE', 'Pywikibot'))
if page.exists():
print(f"\n--- Page Info for '{page.title()}' ---")
print(f"URL: {page.full_url()}")
print(f"Page ID: {page.pageid}")
print(f"Last edited by: {page.last_updated_by.name}")
print("Content snippet (first 200 chars):")
print(page.text[:200])
else:
print(f"\nPage '{page.title()}' does not exist on {site.family.name}:{site.lang}.")