Pywikibot

11.1.0 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a Pywikibot site, attempt to log in (essential for most operations), and retrieve basic information and content from a specified page. Before running, you MUST create a `user-config.py` file with your bot's credentials and site preferences as outlined in the official documentation.

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}.")

view raw JSON →