Topic on Manual talk:Pywikibot

Check if a page exists

5
ElBe (talkcontribs)

If I use

if not pywikibot.Page.exists('Page'):
    #Do something

I get the error

[...]    
    title = self._link.canonical_title()
AttributeError: 'str' object has no attribute '_link'
CRITICAL: Exiting due to uncaught exception <class 'AttributeError'>

What I have to do? --ElBe (talk) 20:31, 20 January 2022 (UTC)

178.209.138.12 (talkcontribs)

I think you should use it like this:

if not pywikibot.Page('Page').exists():

ElBe (talkcontribs)

Thank you! --ElBe (talk) 05:58, 21 January 2022 (UTC)

ElBe (talkcontribs)

It works if I use

[...]
page = pywikibot.Page(site, 'Page')

if not pywikibot.Page(page).exists():
   #Do something

Thank you! --ElBe (talk) 06:09, 21 January 2022 (UTC)

Xqt (talkcontribs)

Hi ElBe, this is not a proper idea but it works by a side effect:

exists()

is a method of a Page object, more precisely of a BasePage object. You have to create the object first to use it:

 page = pywikibot.Page(site, 'Page')
 if not page.exists(): pass  # or do something sensefull

Your example works because

 pywikibot.Page(page)

clones the original page and creates a new Page object. This functionality to implemented to upcast objects e.g.

 fp = pywikibot.FilePage(page)

which creates a FilePage object and provides further methods. But keep in mind that page must be in File: namespace here.

Refer: https://doc.wikimedia.org/pywikibot/master/api_ref/pywikibot.page.html?highlight=exists#pywikibot.page.BasePage.exists

Reply to "Check if a page exists"