pythonpywikibot

How to create and or edit a page with pyWikiBot


The MediaWiki API has an edit function which is available within pywikibot. According to https://doc.wikimedia.org/pywikibot/master/api_ref/pywikibot.site.html

the function is called with a page parameter:

 editpage(page, summary=None, minor=True, notminor=False, bot=True, recreate=True, createonly=False, nocreate=False, watch=None, **kwargs)[source]¶

A page needs a source to be constructed. I could not find an example for this.

E.g.: How to add something to edit summary when using Pywikibot?

has just one line as the accepted answer and does not use site or page. I am confused.

What is the proper approach do create and or edit a page with pyWikiBot directly using python code? (not script ...)

https://github.com/wikimedia/pywikibot/blob/master/pywikibot/page/init.py#L2328

has the constructor:

"""Page: A MediaWiki page."""

    @deprecated_args(defaultNamespace='ns', insite=None)
    def __init__(self, source, title='', ns=0):
        """Instantiate a Page object."""
        if isinstance(source, pywikibot.site.BaseSite):
            if not title:
                raise ValueError('Title must be specified and not empty '
                                 'if source is a Site.')
        super(Page, self).__init__(source, title, ns)

Which is unfortunately not properly documented and part of the 6000 line init.py file having all the classes.

When trying

    newPage=Page(site,pageTitle)
    newPage.text=pageContent

I get

AttributeError: APISite instance has no attribute 'edit'
    site.edit(newPage,'summary')

Solution

  • The following code works:

     from pywikibot.page import Page
    
     newPage=Page(site,pageTitle)
     newPage.text=pageContent
     newPage.save("summary")
    

    see also https://www.mediawiki.org/wiki/Manual:Pywikibot/Create_your_own_script

    It's just unfortunate that the documentation at https://pypi.org/project/pywikibot/ is not using standard python documentation tools.