Jump to content

Manual:Pywikibot/Cookbook/Saving a single page

From mediawiki.org

Here we also have two solutions, but the difference is much less then for getting.

The new and recommended way is save(). As we discussed above, page.text is a property, that means it is always present together with the page object. So when you save the page, the new content will be page.text. save() works without any argument, but a proper edit summary is expected on most wikis, especially from bots, so please always use it. Some wikis also expect that it begins with a Bot: prefix. Please always follow your community's rules.

Save is hard to follow because it calls _save() which calls APISite.editpage(). This is a technical decision that operations writing to the wiki are implemented in APISite class rather then in Page. This way API calls and token things and other disgusting low-level stuff are hidden somewhere in the corner.

On the other hand, put() is the old and traditional way that you will find in several existing scripts on Wikipedia. It takes the text as first argument. It is based on the concept that you have the text in a separate variable:

page = pywikibot.Page(site, 'Special:MyPage')
text = page.get()
# Do something with text
page.put(text, 'Hello, I modified it!')

Putting text equals to

page.text = text
page.save('Hello, I modified it!')

If you look into the code, this is just what put() makes. Just calls save(). So you may create your text in whatever variable and put it, but the recommended way is to place your content into page.text and then save().

The only capability of old put() which is not transferred to save() is the show_diff parameter. If you set it to True, the diff between old and new text will be shown on your screen.

put() can be useful if you began to create a text, and the page object is not available at the beginning. You may also prefer it when you put the same text to several pages. For example in Hungarian Wikipedia we decided to empty old anon talk pages with outdated warnings. Of course,

page.put('This page was emptied.', 'Empty talk pages')

in a loop is more simple than to assign page.text a value each time.

Possible errors

[edit]