### Quickstart: Connect to Wikipedia and get page text Source: https://mwclient.readthedocs.io/en/latest/_sources/index.rst.txt This example demonstrates how to initialize a connection to a MediaWiki site (Wikipedia in this case) and retrieve the text content of a specific page. A user agent string is required for API requests. ```python user_agent = 'MyCoolTool/0.2 (xyz@example.org)' site = mwclient.Site('en.wikipedia.org', clients_useragent=user_agent) page = site.pages['LeipƤjuusto'] page.text() ``` ```python [x for x in page.categories()] ``` -------------------------------- ### Install Documentation Dependencies Source: https://mwclient.readthedocs.io/en/latest/development/index.html Install the dependencies required to build the project documentation locally. ```bash pip install -e '.[docs]' ``` -------------------------------- ### Install mwclient using pip Source: https://mwclient.readthedocs.io/en/latest/_sources/index.rst.txt Use this command to install the mwclient library via pip. Ensure pip is installed and up-to-date. ```bash pip install mwclient ``` -------------------------------- ### Install and Run Tox for Testing Source: https://mwclient.readthedocs.io/en/latest/development/index.html Install tox and run the test suite to ensure code quality and compatibility across different Python versions. ```bash pip install tox tox ``` -------------------------------- ### Install Testing Dependencies and Run Pytest Source: https://mwclient.readthedocs.io/en/latest/development/index.html Install the necessary dependencies for testing, including the testing extras, and run the tests directly with pytest. ```bash pip install -e '.[testing]' py.test ``` -------------------------------- ### Google Style Docstring Example Source: https://mwclient.readthedocs.io/en/latest/development/index.html Example of a Python function with a docstring adhering to the Google style guide, including Args and Returns sections. ```python def my_function(foo: str) -> str: """This is a function that does something. Args: foo: A string to do something with. Returns: A string with the result. """ ``` -------------------------------- ### Install Mwclient in Editable Mode Source: https://mwclient.readthedocs.io/en/latest/development/index.html Install the mwclient library in editable mode using pip for immediate use of your changes during development. ```bash pip install -e . ``` -------------------------------- ### GET /api.php Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Performs a generic API call to the MediaWiki server using the GET method. ```APIDOC ## GET /api.php ### Description Performs a generic API call using the GET method. This is a shorthand for the internal API request handler. ### Method GET ### Endpoint /api.php ### Parameters #### Query Parameters - **action** (string) - Required - The MediaWiki API action to be performed. - **kwargs** (Any) - Optional - Additional parameters to be passed to the API call. ``` -------------------------------- ### Build documentation locally Source: https://mwclient.readthedocs.io/en/latest/_sources/development/index.rst.txt Commands to install documentation dependencies and generate HTML files. ```bash $ pip install -e '.[docs]' ``` ```bash $ cd docs $ make html ``` -------------------------------- ### GET /api.php?action=ask Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Executes a query against Semantic MediaWiki. ```APIDOC ## GET /api.php?action=ask ### Description Ask a query against Semantic MediaWiki. ### Method GET ### Endpoint /api.php?action=ask ### Parameters #### Query Parameters - **query** (string) - Required - The SMW query to be executed - **title** (string) - Optional - Title context for the query ``` -------------------------------- ### Configure development environment Source: https://mwclient.readthedocs.io/en/latest/_sources/development/index.rst.txt Commands to clone the repository, add a fork remote, and perform an editable installation. ```bash $ git clone https://github.com/mwclient/mwclient.git $ cd mwclient $ git remote add fork git@github.com:MYUSERNAME/mwclient.git ``` ```bash $ pip install -e . ``` -------------------------------- ### Release versioning with bump-my-version Source: https://mwclient.readthedocs.io/en/latest/_sources/development/index.rst.txt Install the versioning tool and increment the project version using the specified command. ```bash $ pip install bump-my-version $ bump-my-version bump major|minor|patch ``` -------------------------------- ### GET /api.php?action=query&list=allcategories Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Retrieves all categories on the wiki. ```APIDOC ## GET /api.php?action=query&list=allcategories ### Description Retrieve all categories on the wiki as a generator. ### Method GET ### Endpoint /api.php?action=query&list=allcategories ### Parameters #### Query Parameters - **acfrom** (string) - Optional - The category to start enumerating from - **acto** (string) - Optional - The category to stop enumerating at - **acprefix** (string) - Optional - Search for all category titles that begin with this value - **acdir** (string) - Optional - The direction in which to list ``` -------------------------------- ### GET /api.php?action=query&list=allpages Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Retrieves all pages on the wiki. ```APIDOC ## GET /api.php?action=query&list=allpages ### Description Retrieve all pages on the wiki as a generator. ### Method GET ### Endpoint /api.php?action=query&list=allpages ### Parameters #### Query Parameters - **apfrom** (string) - Optional - The page title to start enumerating from - **apto** (string) - Optional - The page title to stop enumerating at - **apprefix** (string) - Optional - Search for all page titles that begin with this value - **apnamespace** (string) - Optional - The namespace to enumerate - **apfilterredir** (string) - Optional - How to filter redirects - **apminsize** (int) - Optional - Minimum page size in bytes - **apmaxsize** (int) - Optional - Maximum page size in bytes - **apprtype** (string) - Optional - Limit to pages with protection type - **apprlevel** (string) - Optional - Limit to pages with protection level - **apdir** (string) - Optional - The direction in which to list ``` -------------------------------- ### GET /api.php?action=query&list=allimages Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Retrieves all images on the wiki. ```APIDOC ## GET /api.php?action=query&list=allimages ### Description Retrieve all images on the wiki as a generator. ### Method GET ### Endpoint /api.php?action=query&list=allimages ### Parameters #### Query Parameters - **aifrom** (string) - Optional - The image title to start enumerating from - **aito** (string) - Optional - The image title to stop enumerating at - **aiprefix** (string) - Optional - Search for all image titles that begin with this value - **aiminsize** (int) - Optional - Minimum image size in bytes - **aimaxsize** (int) - Optional - Maximum image size in bytes - **aidir** (string) - Optional - The direction in which to list - **aisha1** (string) - Optional - SHA1 hash of image - **aisha1base36** (string) - Optional - SHA1 hash of image in base 36 ``` -------------------------------- ### GET /api.php?action=query&list=alllinks Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Retrieves a list of all links on the wiki. ```APIDOC ## GET /api.php?action=query&list=alllinks ### Description Retrieve a list of all links on the wiki as a generator. ### Method GET ### Endpoint /api.php?action=query&list=alllinks ### Parameters #### Query Parameters - **alfrom** (string) - Optional - The title to start enumerating from - **alto** (string) - Optional - The title to stop enumerating at - **alprefix** (string) - Optional - Search for all titles that begin with this value - **alunique** (bool) - Optional - Only show distinct links - **alprop** (string) - Optional - Which pieces of information to include - **alnamespace** (string) - Optional - The namespace to enumerate ``` -------------------------------- ### GET /api.php?action=query&list=recentchanges Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html List recent changes to the wiki. ```APIDOC ## GET /api.php?action=query&list=recentchanges ### Description List recent changes to the wiki, similar to Special:Recentchanges. ### Method GET ### Parameters #### Query Parameters - **start** (str) - Optional - Start timestamp - **end** (str) - Optional - End timestamp - **dir** (str) - Optional - Direction (default: 'older') - **namespace** (int) - Optional - Namespace filter - **prop** (str) - Optional - Properties to include - **show** (str) - Optional - Show filters - **type** (str) - Optional - Change type - **toponly** (bool) - Optional - Only show top revisions ``` -------------------------------- ### GET /api.php?action=exturlusage Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Retrieve a list of pages that link to a particular domain or URL. ```APIDOC ## GET /api.php?action=exturlusage ### Description Retrieve the list of pages that link to a particular domain or URL, as a generator. This mirrors the Special:LinkSearch function. ### Method GET ### Parameters #### Query Parameters - **query** (str) - Required - Domain or URL to search (e.g., 'bbc.co.uk' or '*.wikipedia.org/wiki/*') - **prop** (str) - Optional - Properties to include - **protocol** (str) - Optional - Protocol to filter by - **namespace** (int) - Optional - Namespace to filter by ### Response #### Success Response (200) - **url** (str) - The URL linked to. - **ns** (int) - Namespace of the wiki page - **pageid** (int) - The ID of the wiki page - **title** (str) - The page title. ``` -------------------------------- ### Run Integration Tests with Tox Source: https://mwclient.readthedocs.io/en/latest/development/index.html Execute the container-based integration tests using tox, which requires Docker or Podman to be installed. ```bash tox -e integration ``` -------------------------------- ### GET /api.php?action=query&list=watchlist Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Lists the pages on the current user's watchlist. ```APIDOC ## GET /api.php?action=query&list=watchlist ### Description List the pages on the current user's watchlist. ### Method GET ### Endpoint /api.php?action=query&list=watchlist ### Parameters #### Query Parameters - **wlallrev** (boolean) - Optional - Include multiple revisions of the same page - **wlstart** (string) - Optional - Timestamp to start listing from - **wlend** (string) - Optional - Timestamp to end listing at - **wlnamespace** (integer) - Optional - Filter by namespace - **wldir** (string) - Optional - Direction to list (default: older) - **wlprop** (string) - Optional - Properties to include - **wlshow** (string) - Optional - Filter items - **wllimit** (integer) - Optional - Limit the number of items ``` -------------------------------- ### GET /api.php?action=query&prop=templates Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/page.html Retrieves a list of templates used on the current page. This method maps to the MediaWiki API:Templates action. ```APIDOC ## GET /api.php?action=query&prop=templates ### Description List templates used on the current page. ### Method GET ### Parameters #### Query Parameters - **namespace** (Namespace) - Optional - The namespace to filter templates by. - **generator** (bool) - Optional - If true, returns a PagePropertyGenerator; otherwise, returns a PageProperty. ### Response #### Success Response (200) - **title** (string) - The title of the template used on the page. ``` -------------------------------- ### GET /api.php?action=query&meta=tokens Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Retrieves a security token for various actions such as editing, watching, or logging in. ```APIDOC ## GET /api.php?action=query&meta=tokens ### Description Retrieves a MediaWiki access token of a specific type. Tokens are cached and can be forced to refresh. ### Method GET ### Endpoint /api.php?action=query&meta=tokens ### Parameters #### Query Parameters - **type** (string) - Required - The type of token to request (e.g., 'csrf', 'login', 'watch'). - **meta** (string) - Required - Set to 'tokens'. ### Response #### Success Response (200) - **query** (object) - The query result containing token information. - **tokens** (object) - Map of token types to their values. ``` -------------------------------- ### Build Documentation Locally Source: https://mwclient.readthedocs.io/en/latest/development/index.html Navigate to the docs directory and run the make command to build the HTML documentation. ```bash cd docs make html ``` -------------------------------- ### Initialize a MediaWiki Site Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Create a new Site instance by specifying the hostname and optional path parameters. ```python >>> import mwclient >>> wikipedia_site = mwclient.Site('en.wikipedia.org') >>> wikia_site = mwclient.Site('vim.wikia.com', path='/') ``` -------------------------------- ### get Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Perform a generic API call using GET. This is a shorthand for calling the main API function with the GET HTTP method. ```APIDOC ## GET /api ### Description Perform a generic API call using GET. ### Method GET ### Endpoint /api ### Parameters #### Query Parameters - **action** (str) - Required - The MediaWiki API action to be performed. - ***args** (Tuple[str, Any]) - Optional - Tupled key-value pairs to be passed to the api.php script as data. Prefer keyword arguments when possible. - ****kwargs** (Any) - Optional - Additional arguments to be passed to the API call. ### Response #### Success Response (200) - **Dict[str, Any]** - The raw response from the API call, as a dictionary. ``` -------------------------------- ### Get Page Text Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/page.html Get the current wikitext of the page, or of a specific section. ```APIDOC ## GET /api/page/text ### Description Get the current wikitext of the page, or of a specific section. If the page does not exist, an empty string is returned. By default, results will be cached. ### Method GET ### Endpoint /api/page/text ### Parameters #### Query Parameters - **section** (string or int) - Optional - Section number or title to only get text from a single section. - **expandtemplates** (boolean) - Optional - Expand templates (default: `False`). - **cache** (boolean) - Optional - Use in-memory caching (default: `True`). ### Response #### Success Response (200) - **wikitext** (string) - The wikitext content of the page or section. ### Response Example ```json { "wikitext": "This is the content of the page." } ``` ``` -------------------------------- ### Site Initialization Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Initializes a connection to a MediaWiki site with various configuration options. ```APIDOC ## Site Initialization ### Description Initializes a connection to a MediaWiki site, setting up various parameters for subsequent API calls. ### Method Constructor ### Endpoint N/A (Class Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import mwclient # Example initialization site = mwclient.Site('example.com', path='/w/', ext='.php') ``` ### Response #### Success Response (200) N/A (Constructor does not return a response in the traditional sense, but initializes the site object). #### Response Example N/A ``` -------------------------------- ### Initialize Site connection Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Constructor for the Site class, handling authentication, session management, and initial site configuration. ```python self, host: str, path: str = '/w/', ext: str = '.php', pool: Optional[requests.Session] = None, retry_timeout: int = 30, max_retries: int = 25, wait_callback: Callable[['Sleeper', int, Optional[Any]], Any] = lambda *x: None, clients_useragent: Optional[str] = None, max_lag: int = 3, compress: bool = True, force_login: bool = True, do_init: bool = True, httpauth: Union[ Tuple[Union[str, bytes], Union[str, bytes]], requests.auth.AuthBase, List[Union[str, bytes]], None, ] = None, connection_options: Optional[MutableMapping[str, Any]] = None, consumer_token: Optional[str] = None, consumer_secret: Optional[str] = None, access_token: Optional[str] = None, access_secret: Optional[str] = None, client_certificate: Optional[Union[str, Tuple[str, str]]] = None, custom_headers: Optional[Mapping[str, str]] = None, scheme: str = 'https', reqs: Optional[MutableMapping[str, Any]] = None ) -> None: # Setup member variables self.host = host self.path = path self.ext = ext self.credentials = None # type: Optional[Tuple[str, str, Optional[str]]] self.compress = compress self.max_lag = str(max_lag) self.force_login = force_login self.logged_in = False if reqs and connection_options: raise ValueError( "reqs is a deprecated alias of connection_options. Do not specify both." ) if reqs: warnings.warn( "reqs is deprecated in mwclient 1.0.0. Use connection_options instead", DeprecationWarning ) connection_options = reqs self.requests = connection_options or {} self.scheme = scheme if 'timeout' not in self.requests: self.requests['timeout'] = 30 # seconds if consumer_token is not None: auth = OAuth1(consumer_token, consumer_secret, access_token, access_secret) elif isinstance(httpauth, (list, tuple)): # workaround weird requests default to encode as latin-1 # https://github.com/mwclient/mwclient/issues/315 # https://github.com/psf/requests/issues/4564 httpauth = [ it.encode("utf-8") if isinstance(it, str) else it for it in httpauth ] auth = HTTPBasicAuth(*httpauth) elif httpauth is None or isinstance(httpauth, (AuthBase,)): auth = httpauth else: # FIXME: Raise a specific exception instead of a generic RuntimeError. raise RuntimeError('Authentication is not a tuple or an instance of AuthBase') self.sleepers = Sleepers(max_retries, retry_timeout, wait_callback) # Site properties self.blocked = False # type: Union[Tuple[str, str], bool] # Is user blocked? self.hasmsg = False # Whether current user has new messages self.groups = [] # type: List[str] # Groups current user is in self.rights = [] # type: List[str] # Rights current user has self.tokens = {} # type: Dict[str, str] # Edit tokens of the current user self.version = None # type: Optional[VersionTuple] self.namespaces = self.default_namespaces # type: Dict[int, str] # Setup connection if pool is None: self.connection = requests.Session() # type: requests.Session self.connection.auth = auth if client_certificate: self.connection.cert = client_certificate # Set User-Agent header field if clients_useragent: ua = clients_useragent + ' ' + USER_AGENT else: ua = USER_AGENT self.connection.headers['User-Agent'] = ua if custom_headers: self.connection.headers.update(custom_headers) else: self.connection = pool # Page generators self.pages = listing.PageList(self) self.categories = listing.PageList(self, namespace=14) self.images = listing.PageList(self, namespace=6) # Compat page generators self.Pages = self.pages self.Categories = self.categories self.Images = self.images # Initialization status self.initialized = False # Upload chunk size in bytes self.chunk_size = 1048576 if do_init: try: self.site_init() except errors.APIError as e: if e.args[0] == 'mwoauth-invalid-authorization': raise errors.OAuthAuthorizationError(self, e.code, e.info) # Private wiki, do init after login if e.args[0] not in {'unknown_action', 'readapidenied'}: raise ``` -------------------------------- ### Configure Site with SSL Client Certificate and Key Tuple Source: https://mwclient.readthedocs.io/en/latest/_sources/user/connecting.rst.txt Alternatively, provide a tuple containing the certificate and key file paths for SSL client authentication. The private key must not be encrypted. ```python >>> site = Site('awesome.site', client_certificate=('client.pem', 'key.pem')) ``` -------------------------------- ### Initialize Site Information Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Populates the site object with current user and site details. This is typically done automatically on object creation. ```python site.site_init() ``` -------------------------------- ### Initialize MediaWiki Site Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Initializes a connection to a MediaWiki site using the Site class. ```APIDOC ## Site Initialization ### Description Creates a new instance of a MediaWiki site identified by its hostname. ### Parameters - **host** (str) - Required - The hostname of a MediaWiki instance. - **path** (str) - Optional - The instances script path. Defaults to /w/. - **ext** (str) - Optional - The file extension used by the MediaWiki API scripts. Defaults to .php. - **scheme** (str) - Optional - The URI scheme to use (http or https). Defaults to https. - **retry_timeout** (int) - Optional - Seconds to sleep for each retry. Defaults to 30. - **max_retries** (int) - Optional - Maximum number of retries. Defaults to 25. ### Request Example import mwclient site = mwclient.Site('en.wikipedia.org') ``` -------------------------------- ### Perform Generic GET API Call Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Executes a generic MediaWiki API call using the GET method. Useful for actions not directly exposed as library methods. ```python site.get('action', 'param1', param2='value') ``` -------------------------------- ### Perform Generic API Call (GET) Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Use this method for generic API calls using the GET HTTP method. It passes all arguments directly to the underlying api() method. ```python def get(self, action: str, *args: Tuple[str, Any], **kwargs: Any) -> Dict[str, Any]: """Perform a generic API call using GET. This is just a shorthand for calling api() with http_method='GET'. All arguments will be passed on. Args: action: The MediaWiki API action to be performed. *args: Tupled key-value pairs to be passed to the `api.php` script as data. In most cases, it is preferable to pass these as keyword arguments instead. This can be useful when the parameter name is a reserved Python keyword (e.g. `from`). **kwargs: Arguments to be passed to the API call. Returns: The raw response from the API call, as a dictionary. """ return self.api(action, 'GET', *args, **kwargs) ``` -------------------------------- ### Get Page Object in mwclient Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/listing.html Retrieves a page object from the site. It handles different namespaces and guesses the namespace if not explicitly provided. Use this to get a specific page by name or ID. ```python def get( self, name: Union[str, int, 'mwclient.page.Page'], info: Optional[Mapping[str, Any]] = None ) -> Union['mwclient.page.Page', 'mwclient.image.Image', 'Category']: """Return the page of name `name` as an object. If self.namespace is not zero, use {namespace}:{name} as the page name, otherwise guess the namespace from the name using `self.guess_namespace`. Args: name: The name of the page as a string, the page ID as an int, or another :class:`Page` object. info: Page info, if already fetched, e.g., when iterating over a list of pages. If not provided, the page info will be fetched from the API. Returns: One of Category, Image or Page (default), according to namespace. """ if self.namespace != 0: full_page_name = f"{self.site.namespaces[self.namespace]}:{name}" \ # type: Union[str, int, 'mwclient.page.Page'] namespace = self.namespace else: full_page_name = name if isinstance(name, str): namespace = self.guess_namespace(name) else: namespace = 0 cls = { 14: Category, 6: mwclient.image.Image, }.get(namespace, mwclient.page.Page) return cls(self.site, full_page_name, info) # type: ignore[no-any-return] ``` -------------------------------- ### Site Class Initialization Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html The Site class allows you to connect to a MediaWiki instance. You can configure various aspects of the connection, such as the host, path, authentication, and retry behavior. ```APIDOC ## Site Class ### Description A MediaWiki site identified by its hostname. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Initialization Parameters - **host** (string) - Required - The hostname of a MediaWiki instance. Must not include a scheme (e.g. `https://`) - use the `scheme` argument instead. - **path** (string) - Optional - The instances script path (where the `index.php` and `api.php` scripts are located). Must contain a trailing slash (`/`). Defaults to `/w/`. - **ext** (string) - Optional - The file extension used by the MediaWiki API scripts. Defaults to `.php`. - **pool** (requests.Session) - Optional - A preexisting :class:`~requests.Session` to be used when executing API requests. When this is set, the `client_certificate`, `clients_useragent`, `custom_headers`, `http_auth` and all OAuth related parameters are all ignored. - **retry_timeout** (int) - Optional - The number of seconds to sleep for each past retry of a failing API request. Defaults to `30`. - **max_retries** (int) - Optional - The maximum number of retries to perform for failing API requests. Defaults to `25`. - **wait_callback** (Callable) - Optional - A callback function to be executed for each failing API request. - **clients_useragent** (string) - Optional - A prefix to be added to the default mwclient user-agent. Should follow the pattern `'{tool_name}/{tool_version} ({contact})'`. - **max_lag** (int) - Optional - A `maxlag` parameter to be used in `index.php` calls. Defaults to `3`. - **compress** (bool) - Optional - Whether to request and accept gzip compressed API responses. Defaults to `True`. - **force_login** (bool) - Optional - Whether to require authentication when editing pages. Set to `False` to allow unauthenticated edits. Defaults to `True`. - **do_init** (bool) - Optional - Whether to automatically initialize the :py:class:`Site` on initialization. When set to `False`, the :py:class:`Site` must be initialized manually using the :py:meth:`.site_init` method. Defaults to `True`. - **httpauth** (Union[AuthBase, Tuple[str, str]]) - Optional - An authentication method to be used when making API requests. This can be either an authentication object as provided by the :py:mod:`requests` library, or a tuple in the form `{username, password}`. - **connection_options** (Dict[str, Any]) - Optional - Additional arguments to be passed to the :py:meth:`requests.Session.request` method when performing API calls. If the `timeout` key is empty, a default timeout of 30 seconds is added. - **consumer_token** (str) - Optional - OAuth1 consumer key for owner-only consumers. - **consumer_secret** (str) - Optional - OAuth1 consumer secret for owner-only consumers. - **access_token** (str) - Optional - OAuth1 access key for owner-only consumers. - **access_secret** (str) - Optional - OAuth1 access secret for owner-only consumers. - **client_certificate** (Union[str, Tuple[str, str], BinaryIO]) - Optional - A client certificate to be added to the session. - **custom_headers** (Mapping[str, str]) - Optional - A dictionary of custom headers to be added to all API requests. - **scheme** (str) - Optional - The URI scheme to use. This should be either `http` or `https` in most cases. Defaults to `https`. ### Examples ```python import mwclient # Connect to English Wikipedia site = mwclient.Site('en.wikipedia.org') # Connect to a Wikia site wikia_site = mwclient.Site('vim.wikia.com', path='/') ``` ### Raises - **RuntimeError**: The authentication passed to the `httpauth` parameter is invalid. You must pass either a tuple or a :class:`requests.auth.AuthBase` object. - **errors.OAuthAuthorizationError**: The OAuth authorization is invalid. - **errors.LoginError**: Login failed, the reason can be obtained from e.code and e.info (where e is the exception object) and will be one of the API:Login errors. The most common error code is "Failed", indicating a wrong username or password. ``` -------------------------------- ### GET /blocks Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Retrieve blocks as a generator. ```APIDOC ## GET /blocks ### Description Retrieve blocks as a generator. ### Method GET ### Endpoint blocks ### Parameters #### Query Parameters - **start** (str) - Optional - The timestamp to start listing from. - **end** (str) - Optional - The timestamp to stop listing at. - **dir** (str) - Optional - Direction to list in (default: older). - **ids** (str) - Optional - List of block IDs to retrieve. - **users** (str) - Optional - List of users to search for. - **limit** (int) - Optional - How many total items to return. - **prop** (str) - Optional - Which properties to get (default: id|user|by|timestamp|expiry|reason|flags). ### Response #### Success Response (200) - **user** (str) - The username or IP address of the user - **id** (str) - The ID of the block - **timestamp** (str) - When the block was added - **expiry** (str) - When the block runs out - **reason** (str) - The reason they are blocked - **allowusertalk** (str) - Present if user is allowed to edit talk page - **by** (str) - The administrator who blocked the user - **nocreate** (str) - Present if account creation is disabled ``` -------------------------------- ### revisions Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Get data about a list of revisions. ```APIDOC ## revisions ### Description Get data about a list of revisions. ### Parameters - **revids** (List[str | int]) - Required - A list of (max 50) revisions. - **prop** (str) - Optional - Which properties to get for each revision. - **slots** (str) - Optional - Slots ### Response - **Return type** (List[Dict[str, Any]]) - A list of revisions. ``` -------------------------------- ### Connect to a MediaWiki site Source: https://mwclient.readthedocs.io/en/latest/user/page-ops.html Initializes a connection to a MediaWiki site using a custom user agent. ```python from mwclient import Site user_agent = 'MyCoolTool/0.2 (xyz@example.org)' site = Site('en.wikipedia.org', clients_useragent=user_agent) ``` -------------------------------- ### GET /deletedrevisions Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Retrieve deleted revisions as a generator. ```APIDOC ## GET /deletedrevisions ### Description Retrieve deleted revisions as a generator. ### Method GET ### Endpoint deletedrevs ### Parameters #### Query Parameters - **start** (str) - Optional - The timestamp to start listing from. - **end** (str) - Optional - The timestamp to stop listing at. - **dir** (str) - Optional - Direction to list in (default: older). - **namespace** (int) - Optional - Only list revisions in these namespaces. - **limit** (int) - Optional - How many total items to return. - **prop** (str) - Optional - Which properties to get (default: user|comment). ``` -------------------------------- ### GET /allusers Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Retrieve all users on the wiki as a generator. ```APIDOC ## GET /allusers ### Description Retrieve all users on the wiki as a generator. ### Method GET ### Endpoint allusers ### Parameters #### Query Parameters - **start** (str) - Optional - The user to start listing from. - **prefix** (str) - Optional - Search for all users that begin with this string. - **group** (str) - Optional - Only list users in this group. - **prop** (str) - Optional - Which pieces of information to include. - **limit** (int) - Optional - How many total items to return. - **witheditsonly** (bool) - Optional - Only list users who have made edits. - **activeusers** (bool) - Optional - Only list users who have been active in the last 30 days. - **rights** (str) - Optional - Only list users with these rights. - **end** (str) - Optional - The user to stop listing at. ``` -------------------------------- ### Clone and Configure Mwclient Repository Source: https://mwclient.readthedocs.io/en/latest/development/index.html Clone the mwclient repository and set up your fork as a remote for contributing. ```bash git clone https://github.com/mwclient/mwclient.git cd mwclient git remote add fork git@github.com:MYUSERNAME/mwclient.git ``` -------------------------------- ### GET /users Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Retrieves information about a list of users. ```APIDOC ## GET /users ### Description Fetches metadata and information for a list of users. ### Parameters #### Query Parameters - **users** (Iterable[str]) - Required - List of usernames. - **prop** (str) - Optional - Properties to fetch (default: blockinfo|groups|editcount). ### Response #### Success Response (200) - **users** (List) - List of user information objects. ``` -------------------------------- ### GET allcategories Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Retrieves all categories on the wiki as a generator. ```APIDOC ## GET allcategories ### Description Retrieve all categories on the wiki as a generator. ### Parameters #### Query Parameters - **start** (str) - Optional - The category to start listing from. - **prefix** (str) - Optional - Search for all category titles that begin with this value. - **dir** (str) - Optional - The direction in which to list (ascending or descending). - **limit** (int) - Optional - How many total categories to return. - **generator** (bool) - Optional - Whether to return as a generator. Defaults to True. ``` -------------------------------- ### Perform Client Login Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Logs into the wiki using provided credentials. Handles both successful logins and multi-step authentication processes. Raises LoginError on failure. ```python >>> try: ... site.clientlogin(username='myusername', password='secret') ... except mwclient.errors.LoginError as e: ... print(f'Could not login to MediaWiki: {e}' ) ``` -------------------------------- ### GET /api/revisions Source: https://mwclient.readthedocs.io/en/latest/reference/page.html List revisions of the current page. ```APIDOC ## GET /api/revisions ### Description List revisions of the current page. ### Parameters #### Query Parameters - **startid** (int|None) - Optional - Revision ID to start listing from - **endid** (int|None) - Optional - Revision ID to stop listing at - **start** (str|None) - Optional - Timestamp to start listing from - **end** (str|None) - Optional - Timestamp to end listing at - **dir** (str) - Optional - Direction: 'older' or 'newer' - **user** (str|None) - Optional - Filter by user - **excludeuser** (str|None) - Optional - Exclude revisions by user - **prop** (str) - Optional - Properties to get - **expandtemplates** (bool) - Optional - Expand templates in content - **section** (str|None) - Optional - Section number ``` -------------------------------- ### POST /api.php?action=clientlogin Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Performs a modern, multi-step authentication process for MediaWiki 1.27+. ```APIDOC ## POST /api.php?action=clientlogin ### Description Authenticates a user using the clientlogin method, which supports multi-step authentication flows. ### Method POST ### Endpoint /api.php?action=clientlogin ### Parameters #### Request Body - **username** (string) - Optional - The username (required for classic login). - **password** (string) - Optional - The password (required for classic login). - **logintoken** (string) - Required - The token obtained from the API. - **loginreturnurl** (string) - Optional - The URL to return to after login. - **logincontinue** (boolean) - Optional - Flag to continue a multi-step login. ### Response #### Success Response (200) - **status** (string) - The status of the authentication process. #### Response Example { "clientlogin": { "status": "PASS" } } ``` -------------------------------- ### GET /api.php (Search) Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Performs a full-text search on the wiki. ```APIDOC ## GET /api.php (Search) ### Description Performs a full-text search on the wiki. This endpoint allows users to search for pages based on a query string, with options to specify the namespace and whether to include redirects. ### Method GET ### Endpoint /api.php ### Parameters #### Query Parameters - **action** (string) - Required - 'query' - **list** (string) - Required - 'search' - **srsearch** (string) - Required - The query string to search for. - **srnamespace** (string) - Optional - The namespace to search within. Defaults to '0'. - **srwhat** (string) - Optional - Search scope: 'text' for fulltext, or 'title' for titles only. Availability depends on the search backend. - **redirects** (boolean) - Optional - Include redirect pages in the search. (Option removed in MediaWiki 1.23). - **limit** (integer) - Optional - Maximum number of results to return. - **max_items** (integer) - Optional - Maximum number of items to fetch across all API calls. - **api_chunk_size** (integer) - Optional - Number of items to fetch per API call. ### Request Example ```json { "action": "query", "list": "search", "srsearch": "prefix:Template:Citation/", "srnamespace": "0", "limit": 10 } ``` ### Response #### Success Response (200) - **query.searchinfo** (object) - Information about the search results. - **totalhits** (integer) - The total number of pages matching the search query. - **query.search** (array) - A list of search result objects. - **ns** (integer) - The namespace of the page. - **title** (string) - The title of the page. - **pageid** (integer) - The ID of the page. - **size** (integer) - The size of the page in bytes. - **wordcount** (integer) - The word count of the page. - **snippet** (string) - A snippet of the page content highlighting the search terms. - **timestamp** (string) - The last modification timestamp of the page. #### Response Example ```json { "query": { "searchinfo": { "totalhits": 50 }, "search": [ { "ns": 10, "title": "Template:Citation/core", "pageid": 12345, "size": 5000, "wordcount": 1000, "snippet": "... This is a template for citations ...", "timestamp": "2023-10-26T14:30:00Z" } ] } } ``` ``` -------------------------------- ### Upload a file to MediaWiki Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Demonstrates standard file upload and asynchronous upload workflows using file keys. ```python >>> client.upload(open('somefile', 'rb'), filename='somefile.jpg', description='Some description') ``` ```python >>> response = client.upload(open('somefile','rb'), filename='somefile.jpg', description='Some description', stash=True) ``` ```python >>> client.upload(filekey=response["filekey"], asynchronous=True) ``` -------------------------------- ### POST /api.php?action=expandtemplates Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/client.html Expands wikitext templates. ```APIDOC ## POST /api.php?action=expandtemplates ### Description Takes wikitext and expands templates. ### Method POST ### Endpoint /api.php?action=expandtemplates ### Parameters #### Request Body - **text** (string) - Required - Wikitext to convert - **title** (string) - Optional - Title of the page - **generatexml** (boolean) - Optional - Generate the XML parse tree ``` -------------------------------- ### Site.clientlogin Source: https://mwclient.readthedocs.io/en/latest/reference/site.html Logs in to the wiki using a username and password. Returns True on success or a response for multi-step logins. Raises errors on failure. ```APIDOC ## POST /api.php (clientlogin) ### Description Logs in to the wiki using a username and password. Returns True on success or a response for multi-step logins. Raises errors on failure. ### Method POST ### Endpoint /api.php ### Parameters #### Request Body - **username** (string) - Required - The username for login. - **password** (string) - Required - The password for login. - **cookies** (object) - Optional - Custom cookies to include with the log-in request. - **kwargs** (object) - Optional - Custom variables for clientlogin, such as `loginmergerequestfields`, `loginpreservestate`, `loginreturnurl`, `logincontinue`, `logintoken`, and other authentication-specific parameters. ### Request Example ```json { "username": "myusername", "password": "secret" } ``` ### Response #### Success Response (200) - **bool** (boolean) - True if login was successful. - **dict** (object) - Response data if it's a multi-step login process. #### Response Example ```json true ``` ### Error Handling - **LoginError** - Raised if login fails. Check `e.code` and `e.info` for details (e.g., 'Failed' for incorrect credentials). - **MaximumRetriesExceeded** - Raised if the API call to log in fails after exhausting all retries. - **APIError** - Raised for other API-related errors. ``` -------------------------------- ### GET /extlinks Source: https://mwclient.readthedocs.io/en/latest/_modules/mwclient/page.html Lists external links from the current page. ```APIDOC ## GET /extlinks ### Description Lists external links found on the current page. This API call retrieves all URLs that are linked from a specific page. ### Method GET ### Endpoint /w/api.php ### Parameters #### Query Parameters - **action** (string) - Required - Set to 'query'. - **list** (string) - Required - Set to 'extlinks'. - **ellimit** (string) - Optional - The maximum number of results to return. - **eltitle** (string) - Required - The title of the page for which to retrieve external links. - **elnamespace** (integer) - Optional - Restricts the search to a given namespace. - **elprefix** (string) - Optional - Filter external links by prefix. ### Request Example ```json { "action": "query", "list": "extlinks", "eltitle": "PageWithExternalLinks", "ellimit": "5" } ``` ### Response #### Success Response (200) - **query.extlinks** (array) - A list of external links found on the page. - Each item is a key-value pair where the key is the domain and the value is a list of URLs from that domain. #### Response Example ```json { "query": { "extlinks": [ { "example.com": [ "http://www.example.com/page1", "http://www.example.com/page2" ] }, { "another-domain.org": [ "http://another-domain.org/resource" ] } ] } } ``` ``` -------------------------------- ### Configure Site with SSL Client Certificate Source: https://mwclient.readthedocs.io/en/latest/_sources/user/connecting.rst.txt Configure the Site object to use SSL client certificate authentication by providing the path to the certificate file. The private key must not be encrypted. ```python >>> site = Site('awesome.site', client_certificate='/path/to/client-and-key.pem') ``` -------------------------------- ### Configure connection scheme and path Source: https://mwclient.readthedocs.io/en/latest/_sources/user/connecting.rst.txt Specify the protocol scheme or a custom API script path if the default /w/ path is incorrect. ```python site = Site('test.wikipedia.org', scheme='http') ``` ```python site = Site('my-awesome-wiki.org', path='/wiki/') ```