import pywikibot
testwiki = pywikibot.Site()
testwiki
APISite("test", "wikipedia")
enwiki = pywikibot.Site(code="en", fam="wikipedia")
enwiki
APISite("en", "wikipedia")
testwiki.login()
print('Logged in user is:', testwiki.user())
Logged in user is: Sarvani241098
demo_page = pywikibot.Page(testwiki, 'User:AbdealiJK/Pywikibot_Tutorial')
demo_page
Page('User:AbdealiJK/Pywikibot Tutorial')
print(demo_page.text)
Hi !

This is a example page for the pywikibot tutorial users to see.
print("Check if page exists:", demo_page.exists())
Check if page exists: True
print("Title of the page:", demo_page.title())
Title of the page: User:AbdealiJK/Pywikibot Tutorial
print("Contributors of the page:", demo_page.contributors())
Contributors of the page: Counter({'AbdealiJK': 2})
print("Last edit made on page:", demo_page.editTime())
Last edit made on page: 2016-09-13T11:43:35Z
sandbox = pywikibot.Page(testwiki, 'User:sarvani241098' + testwiki.user() + '/Sandbox')
sandbox
Page('User:Sarvani241098Sarvani241098/Sandbox')
sandbox.text ="""
== My Profile ==

Hello!

My name is '{name}.'

I am from {hometown} and am learning how to use pywikibot !

This page has been written using the pywikibot API""".format(name='sarvani',hometown='vijayawada')
sandbox.save()
Page [[User:Sarvani241098Sarvani241098/Sandbox]] saved
print(sandbox.text)
== My Profile ==

Hello!

My name is '{name}.'

I am from {hometown} and am learning how to use pywikibot !

This page has been written using the pywikibot API.format(name='sarvani',hometown='vijayawada')
print(sandbox.text)
== My Profile ==

Hello!

My name is 'sarvani.'

I am from vijayawada and am learning how to use pywikibot !

This page has been written using the pywikibot API
from IPython.display import IFrame
IFrame(sandbox.full_url(), width="100%", height="400px")
python = pywikibot.Page(enwiki, 'Python_(programming_language)')
python
Page('Python (programming language)')
list(python.categories())
[Category('Category:Articles with DMOZ links'),
 Category('Category:Class-based programming languages'),
 Category('Category:Cross-platform free software'),
 Category('Category:Dutch inventions'),
 Category('Category:Dynamically typed programming languages'),
 Category('Category:Educational programming languages'),
 Category('Category:Good articles'),
 Category('Category:High-level programming languages'),
 Category('Category:Object-oriented programming languages'),
 Category('Category:Programming languages created in 1991'),
 Category('Category:Python (programming language)'),
 Category('Category:Scripting languages'),
 Category('Category:Text-oriented programming languages'),
 Category('Category:Use dmy dates from August 2015'),
 Category('Category:Wikipedia articles needing page number citations from January 2012'),
 Category('Category:Wikipedia articles with GND identifiers'),
 Category('Category:Wikipedia articles with LCCN identifiers')]
pywikibot.textlib.getCategoryLinks(python.text)
[Category('Category:Class-based programming languages'),
 Category('Category:Cross-platform free software'),
 Category('Category:Dutch inventions'),
 Category('Category:Dynamically typed programming languages'),
 Category('Category:Educational programming languages'),
 Category('Category:High-level programming languages'),
 Category('Category:Object-oriented programming languages'),
 Category('Category:Programming languages created in 1991'),
 Category('Category:Python (programming language)'),
 Category('Category:Scripting languages'),
 Category('Category:Text-oriented programming languages')]
print("Text categories in page:", len(pywikibot.textlib.getCategoryLinks(python.text)))
Text categories in page: 11
print("All categories associated with page:", len(list(python.categories())))
All categories associated with page: 17
new_text = pywikibot.textlib.removeCategoryLinks(python.text)
print("List of categories after the remove function:", pywikibot.textlib.getCategoryLinks(new_text))
List of categories after the remove function: []
import pywikibot.pagegenerators

wiki_projects = pywikibot.pagegenerators.CategorizedPageGenerator(
    pywikibot.Category(enwiki, 'Category:Wikimedia projects'),
    recurse=False)

from pprint import pprint
pprint(list(wiki_projects))
[Page('Wikimedia project'),
 Page('Wikibooks'),
 Page('Wikimedia Commons'),
 Page('Wiktionary'),
 Page('Wikinews'),
 Page('Wikiquote'),
 Page('Wikisource'),
 Page('Wikispecies'),
 Page('Wikidata'),
 Page('Wikipedia'),
 Page('Wikiversity'),
 Page('Wikivoyage')]
import pywikibot
wikidata = pywikibot.Site('wikidata', 'wikidata')
wikidata
DataSite("wikidata", "wikidata")
testwikidata = pywikibot.Site('test', 'wikidata')
testwikidata
DataSite("test", "wikidata")
itempage = pywikibot.ItemPage(wikidata, "Q42")  # Q42 is Douglas Adams
itempage
ItemPage('Q42')
itempage.get()
WARNING: API error mwoauth-invalid-authorization-invalid-user: The authorization headers in your request are for a user that does not exist here
---------------------------------------------------------------------------
NoUsername                                Traceback (most recent call last)
<ipython-input-34-2b4751ffe47a> in <module>()
----> 1 itempage.get()

/srv/paws/lib/python3.4/site-packages/pywikibot/page.py in get(self, force, get_redirect, *args, **kwargs)
   3924         @raise NotImplementedError: a value in args or kwargs
   3925         """
-> 3926         data = super(ItemPage, self).get(force, *args, **kwargs)
   3927 
   3928         if self.isRedirectPage() and not get_redirect:

/srv/paws/lib/python3.4/site-packages/pywikibot/page.py in get(self, force, *args, **kwargs)
   3539                 self.claims[pid] = []
   3540                 for claim in self._content['claims'][pid]:
-> 3541                     c = Claim.fromJSON(self.repo, claim)
   3542                     c.on_item = self
   3543                     self.claims[pid].append(c)

/srv/paws/lib/python3.4/site-packages/pywikibot/page.py in fromJSON(cls, site, data)
   4335             # The default covers string, url types
   4336             claim.target = Claim.TARGET_CONVERTER.get(
-> 4337                 claim.type, lambda value, site: value)(value, site)
   4338         if 'rank' in data:  # References/Qualifiers don't have ranks
   4339             claim.rank = data['rank']

/srv/paws/lib/python3.4/site-packages/pywikibot/page.py in <lambda>(value, site)
   4275             ItemPage(site, 'Q' + str(value['numeric-id'])),
   4276         'commonsMedia': lambda value, site:
-> 4277             FilePage(pywikibot.Site('commons', 'commons'), value),
   4278         'globe-coordinate': pywikibot.Coordinate.fromWikibase,
   4279         'time': lambda value, site: pywikibot.WbTime.fromWikibase(value),

/srv/paws/lib/python3.4/site-packages/pywikibot/tools/__init__.py in wrapper(*__args, **__kw)
   1445                              cls, depth)
   1446                     del __kw[old_arg]
-> 1447             return obj(*__args, **__kw)
   1448 
   1449         if not __debug__:

/srv/paws/lib/python3.4/site-packages/pywikibot/page.py in __init__(self, source, title)
   2300         """Constructor."""
   2301         self._file_revisions = {}  # dictionary to cache File history.
-> 2302         super(FilePage, self).__init__(source, title, 6)
   2303         if self.namespace() != 6:
   2304             raise ValueError(u"'%s' is not in the file namespace!" % title)

/srv/paws/lib/python3.4/site-packages/pywikibot/tools/__init__.py in wrapper(*__args, **__kw)
   1445                              cls, depth)
   1446                     del __kw[old_arg]
-> 1447             return obj(*__args, **__kw)
   1448 
   1449         if not __debug__:

/srv/paws/lib/python3.4/site-packages/pywikibot/tools/__init__.py in wrapper(*__args, **__kw)
   1445                              cls, depth)
   1446                     del __kw[old_arg]
-> 1447             return obj(*__args, **__kw)
   1448 
   1449         if not __debug__:

/srv/paws/lib/python3.4/site-packages/pywikibot/page.py in __init__(self, source, title, ns)
   2176                 raise ValueError(u'Title must be specified and not empty '
   2177                                  'if source is a Site.')
-> 2178         super(Page, self).__init__(source, title, ns)
   2179 
   2180     @deprecate_arg("get_redirect", None)

/srv/paws/lib/python3.4/site-packages/pywikibot/page.py in __init__(self, source, title, ns)
    158 
    159         if isinstance(source, pywikibot.site.BaseSite):
--> 160             self._link = Link(title, source=source, defaultNamespace=ns)
    161             self._revisions = {}
    162         elif isinstance(source, Page):

/srv/paws/lib/python3.4/site-packages/pywikibot/page.py in __init__(self, text, source, defaultNamespace)
   4942         # See bug T104864, defaultNamespace might have been deleted.
   4943         try:
-> 4944             self._defaultns = self._source.namespaces[defaultNamespace]
   4945         except KeyError:
   4946             self._defaultns = defaultNamespace

/srv/paws/lib/python3.4/site-packages/pywikibot/site.py in namespaces(self)
   1012         """Return dict of valid namespaces on this wiki."""
   1013         if not hasattr(self, '_namespaces'):
-> 1014             self._namespaces = NamespacesDict(self._build_namespaces())
   1015         return self._namespaces
   1016 

/srv/paws/lib/python3.4/site-packages/pywikibot/site.py in _build_namespaces(self)
   2608         # For versions lower than 1.14, APISite needs to override
   2609         # the defaults defined in Namespace.
-> 2610         is_mw114 = MediaWikiVersion(self.version()) >= MediaWikiVersion('1.14')
   2611 
   2612         for nsdata in self.siteinfo.get('namespaces', cache=False).values():

/srv/paws/lib/python3.4/site-packages/pywikibot/site.py in version(self)
   2715         if not version:
   2716             try:
-> 2717                 version = self.siteinfo.get('generator', expiry=1).split(' ')[1]
   2718             except pywikibot.data.api.APIError:
   2719                 # May occur if you are not logged in (no API read permissions).

/srv/paws/lib/python3.4/site-packages/pywikibot/site.py in get(self, key, get_default, cache, expiry)
   1674                 elif not Siteinfo._is_expired(cached[1], expiry):
   1675                     return copy.deepcopy(cached[0])
-> 1676         preloaded = self._get_general(key, expiry)
   1677         if not preloaded:
   1678             preloaded = self._get_siteinfo(key, expiry)[key]

/srv/paws/lib/python3.4/site-packages/pywikibot/site.py in _get_general(self, key, expiry)
   1620                         u"', '".join(props)), _logger)
   1621             props += ['general']
-> 1622             default_info = self._get_siteinfo(props, expiry)
   1623             for prop in props:
   1624                 self._cache[prop] = default_info[prop]

/srv/paws/lib/python3.4/site-packages/pywikibot/site.py in _get_siteinfo(self, prop, expiry)
   1546             # warnings are handled later
   1547             request._warning_handler = warn_handler
-> 1548             data = request.submit()
   1549         except api.APIError as e:
   1550             if e.code == 'siunknown_siprop':

/srv/paws/lib/python3.4/site-packages/pywikibot/data/api.py in submit(self)
   2340         cached_available = self._load_cache()
   2341         if not cached_available:
-> 2342             self._data = super(CachedRequest, self).submit()
   2343             self._write_cache(self._data)
   2344         else:

/srv/paws/lib/python3.4/site-packages/pywikibot/data/api.py in submit(self)
   2173                     continue
   2174                 raise NoUsername('Failed OAuth authentication for %s: %s'
-> 2175                                  % (self.site, info))
   2176             # raise error
   2177             try:

NoUsername: Failed OAuth authentication for commons:commons: The authorization headers in your request are for a user that does not exist here
itemdata['labels']
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-35-1110ecf354dd> in <module>()
----> 1 itemdata['labels']

NameError: name 'itemdata' is not defined