import pywikibot
import requests
import json
site = pywikibot.Site('wikidata', 'wikidata')
repo = site.data_repository()
site.login()
item = pywikibot.ItemPage(repo, 'Q5')
item.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-13-7ad3ed485c96> in <module>()
      1 site.login()
      2 item = pywikibot.ItemPage(repo, 'Q5')
----> 3 item.get()

/srv/paws/pwb/pywikibot/page.py in get(self, force, get_redirect, *args, **kwargs)
   4245         @raise NotImplementedError: a value in args or kwargs
   4246         """
-> 4247         data = super(ItemPage, self).get(force, *args, **kwargs)
   4248 
   4249         if self.isRedirectPage() and not get_redirect:

/srv/paws/pwb/pywikibot/page.py in get(self, force, *args, **kwargs)
   3800                 self.claims[pid] = []
   3801                 for claim in self._content['claims'][pid]:
-> 3802                     c = Claim.fromJSON(self.repo, claim)
   3803                     c.on_item = self
   3804                     self.claims[pid].append(c)

/srv/paws/pwb/pywikibot/page.py in fromJSON(cls, site, data)
   4703             if claim.type in cls.types or claim.type == 'wikibase-property':
   4704                 claim.target = cls.TARGET_CONVERTER.get(
-> 4705                     claim.type, lambda value, site: value)(value, site)
   4706             else:
   4707                 pywikibot.warning(

/srv/paws/pwb/pywikibot/page.py in <lambda>(value, site)
   4640             PropertyPage(site, 'P' + str(value['numeric-id'])),
   4641         'commonsMedia': lambda value, site:
-> 4642             FilePage(pywikibot.Site('commons', 'commons'), value),  # T90492
   4643         'globe-coordinate': pywikibot.Coordinate.fromWikibase,
   4644         'geo-shape': pywikibot.WbGeoShape.fromWikibase,

/srv/paws/pwb/pywikibot/tools/__init__.py in wrapper(*__args, **__kw)
   1456                              cls, depth)
   1457                     del __kw[old_arg]
-> 1458             return obj(*__args, **__kw)
   1459 
   1460         if not __debug__:

/srv/paws/pwb/pywikibot/page.py in __init__(self, source, title)
   2390         """Constructor."""
   2391         self._file_revisions = {}  # dictionary to cache File history.
-> 2392         super(FilePage, self).__init__(source, title, 6)
   2393         if self.namespace() != 6:
   2394             raise ValueError(u"'%s' is not in the file namespace!" % title)

/srv/paws/pwb/pywikibot/tools/__init__.py in wrapper(*__args, **__kw)
   1456                              cls, depth)
   1457                     del __kw[old_arg]
-> 1458             return obj(*__args, **__kw)
   1459 
   1460         if not __debug__:

/srv/paws/pwb/pywikibot/page.py in __init__(self, source, title, ns)
   2240                 raise ValueError(u'Title must be specified and not empty '
   2241                                  'if source is a Site.')
-> 2242         super(Page, self).__init__(source, title, ns)
   2243 
   2244     @property

/srv/paws/pwb/pywikibot/page.py in __init__(self, source, title, ns)
    202 
    203         if isinstance(source, pywikibot.site.BaseSite):
--> 204             self._link = Link(title, source=source, defaultNamespace=ns)
    205             self._revisions = {}
    206         elif isinstance(source, Page):

/srv/paws/pwb/pywikibot/page.py in __init__(self, text, source, defaultNamespace)
   5327         # See bug T104864, defaultNamespace might have been deleted.
   5328         try:
-> 5329             self._defaultns = self._source.namespaces[defaultNamespace]
   5330         except KeyError:
   5331             self._defaultns = defaultNamespace

/srv/paws/pwb/pywikibot/site.py in namespaces(self)
   1016         """Return dict of valid namespaces on this wiki."""
   1017         if not hasattr(self, '_namespaces'):
-> 1018             self._namespaces = NamespacesDict(self._build_namespaces())
   1019         return self._namespaces
   1020 

/srv/paws/pwb/pywikibot/site.py in _build_namespaces(self)
   2623         # For versions lower than 1.14, APISite needs to override
   2624         # the defaults defined in Namespace.
-> 2625         is_mw114 = MediaWikiVersion(self.version()) >= MediaWikiVersion('1.14')
   2626 
   2627         for nsdata in self.siteinfo.get('namespaces', cache=False).values():

/srv/paws/pwb/pywikibot/site.py in version(self)
   2737             try:
   2738                 version = self.siteinfo.get('generator',
-> 2739                                             expiry=1).split(' ')[1]
   2740             except pywikibot.data.api.APIError:
   2741                 # May occur if you are not logged in (no API read permissions).

/srv/paws/pwb/pywikibot/site.py in get(self, key, get_default, cache, expiry)
   1679                 elif not Siteinfo._is_expired(cached[1], expiry):
   1680                     return copy.deepcopy(cached[0])
-> 1681         preloaded = self._get_general(key, expiry)
   1682         if not preloaded:
   1683             preloaded = self._get_siteinfo(key, expiry)[key]

/srv/paws/pwb/pywikibot/site.py in _get_general(self, key, expiry)
   1625                     .format("', '".join(props)), _logger)
   1626             props += ['general']
-> 1627             default_info = self._get_siteinfo(props, expiry)
   1628             for prop in props:
   1629                 self._cache[prop] = default_info[prop]

/srv/paws/pwb/pywikibot/site.py in _get_siteinfo(self, prop, expiry)
   1550             # warnings are handled later
   1551             request._warning_handler = warn_handler
-> 1552             data = request.submit()
   1553         except api.APIError as e:
   1554             if e.code == 'siunknown_siprop':

/srv/paws/pwb/pywikibot/data/api.py in submit(self)
   2353         cached_available = self._load_cache()
   2354         if not cached_available:
-> 2355             self._data = super(CachedRequest, self).submit()
   2356             self._write_cache(self._data)
   2357         else:

/srv/paws/pwb/pywikibot/data/api.py in submit(self)
   2183                     continue
   2184                 raise NoUsername('Failed OAuth authentication for %s: %s'
-> 2185                                  % (self.site, info))
   2186             if code == 'cirrussearch-too-busy-error':  # T170647
   2187                 self.wait()

NoUsername: Failed OAuth authentication for commons:commons: The authorization headers in your request are for a user that does not exist here
payload = {
    'query': 'select ?item { ?item wdt:P31 wd:Q11424; wdt:P407 ?l; wdt:P364 ?l}',
    'format': 'json'
}
r = requests.get('https://query.wikidata.org/bigdata/namespace/wdq/sparql',params=payload)
data = r.json()
for m in data['results']['bindings']:
    val = m['item']['value'].split('http://www.wikidata.org/entity/')
    print(val[1])
    item = pywikibot.ItemPage(repo, val[1])
    item.get()
Q29658
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-10-36f0e5e4d693> in <module>()
      9     print(val[1])
     10     item = pywikibot.ItemPage(repo, val[1])
---> 11     item.get()

/srv/paws/pwb/pywikibot/page.py in get(self, force, get_redirect, *args, **kwargs)
   4245         @raise NotImplementedError: a value in args or kwargs
   4246         """
-> 4247         data = super(ItemPage, self).get(force, *args, **kwargs)
   4248 
   4249         if self.isRedirectPage() and not get_redirect:

/srv/paws/pwb/pywikibot/page.py in get(self, force, *args, **kwargs)
   3800                 self.claims[pid] = []
   3801                 for claim in self._content['claims'][pid]:
-> 3802                     c = Claim.fromJSON(self.repo, claim)
   3803                     c.on_item = self
   3804                     self.claims[pid].append(c)

/srv/paws/pwb/pywikibot/page.py in fromJSON(cls, site, data)
   4703             if claim.type in cls.types or claim.type == 'wikibase-property':
   4704                 claim.target = cls.TARGET_CONVERTER.get(
-> 4705                     claim.type, lambda value, site: value)(value, site)
   4706             else:
   4707                 pywikibot.warning(

/srv/paws/pwb/pywikibot/page.py in <lambda>(value, site)
   4640             PropertyPage(site, 'P' + str(value['numeric-id'])),
   4641         'commonsMedia': lambda value, site:
-> 4642             FilePage(pywikibot.Site('commons', 'commons'), value),  # T90492
   4643         'globe-coordinate': pywikibot.Coordinate.fromWikibase,
   4644         'geo-shape': pywikibot.WbGeoShape.fromWikibase,

/srv/paws/pwb/pywikibot/tools/__init__.py in wrapper(*__args, **__kw)
   1456                              cls, depth)
   1457                     del __kw[old_arg]
-> 1458             return obj(*__args, **__kw)
   1459 
   1460         if not __debug__:

/srv/paws/pwb/pywikibot/page.py in __init__(self, source, title)
   2390         """Constructor."""
   2391         self._file_revisions = {}  # dictionary to cache File history.
-> 2392         super(FilePage, self).__init__(source, title, 6)
   2393         if self.namespace() != 6:
   2394             raise ValueError(u"'%s' is not in the file namespace!" % title)

/srv/paws/pwb/pywikibot/tools/__init__.py in wrapper(*__args, **__kw)
   1456                              cls, depth)
   1457                     del __kw[old_arg]
-> 1458             return obj(*__args, **__kw)
   1459 
   1460         if not __debug__:

/srv/paws/pwb/pywikibot/page.py in __init__(self, source, title, ns)
   2240                 raise ValueError(u'Title must be specified and not empty '
   2241                                  'if source is a Site.')
-> 2242         super(Page, self).__init__(source, title, ns)
   2243 
   2244     @property

/srv/paws/pwb/pywikibot/page.py in __init__(self, source, title, ns)
    202 
    203         if isinstance(source, pywikibot.site.BaseSite):
--> 204             self._link = Link(title, source=source, defaultNamespace=ns)
    205             self._revisions = {}
    206         elif isinstance(source, Page):

/srv/paws/pwb/pywikibot/page.py in __init__(self, text, source, defaultNamespace)
   5327         # See bug T104864, defaultNamespace might have been deleted.
   5328         try:
-> 5329             self._defaultns = self._source.namespaces[defaultNamespace]
   5330         except KeyError:
   5331             self._defaultns = defaultNamespace

/srv/paws/pwb/pywikibot/site.py in namespaces(self)
   1016         """Return dict of valid namespaces on this wiki."""
   1017         if not hasattr(self, '_namespaces'):
-> 1018             self._namespaces = NamespacesDict(self._build_namespaces())
   1019         return self._namespaces
   1020 

/srv/paws/pwb/pywikibot/site.py in _build_namespaces(self)
   2623         # For versions lower than 1.14, APISite needs to override
   2624         # the defaults defined in Namespace.
-> 2625         is_mw114 = MediaWikiVersion(self.version()) >= MediaWikiVersion('1.14')
   2626 
   2627         for nsdata in self.siteinfo.get('namespaces', cache=False).values():

/srv/paws/pwb/pywikibot/site.py in version(self)
   2737             try:
   2738                 version = self.siteinfo.get('generator',
-> 2739                                             expiry=1).split(' ')[1]
   2740             except pywikibot.data.api.APIError:
   2741                 # May occur if you are not logged in (no API read permissions).

/srv/paws/pwb/pywikibot/site.py in get(self, key, get_default, cache, expiry)
   1679                 elif not Siteinfo._is_expired(cached[1], expiry):
   1680                     return copy.deepcopy(cached[0])
-> 1681         preloaded = self._get_general(key, expiry)
   1682         if not preloaded:
   1683             preloaded = self._get_siteinfo(key, expiry)[key]

/srv/paws/pwb/pywikibot/site.py in _get_general(self, key, expiry)
   1625                     .format("', '".join(props)), _logger)
   1626             props += ['general']
-> 1627             default_info = self._get_siteinfo(props, expiry)
   1628             for prop in props:
   1629                 self._cache[prop] = default_info[prop]

/srv/paws/pwb/pywikibot/site.py in _get_siteinfo(self, prop, expiry)
   1550             # warnings are handled later
   1551             request._warning_handler = warn_handler
-> 1552             data = request.submit()
   1553         except api.APIError as e:
   1554             if e.code == 'siunknown_siprop':

/srv/paws/pwb/pywikibot/data/api.py in submit(self)
   2353         cached_available = self._load_cache()
   2354         if not cached_available:
-> 2355             self._data = super(CachedRequest, self).submit()
   2356             self._write_cache(self._data)
   2357         else:

/srv/paws/pwb/pywikibot/data/api.py in submit(self)
   2183                     continue
   2184                 raise NoUsername('Failed OAuth authentication for %s: %s'
-> 2185                                  % (self.site, info))
   2186             if code == 'cirrussearch-too-busy-error':  # T170647
   2187                 self.wait()

NoUsername: Failed OAuth authentication for commons:commons: The authorization headers in your request are for a user that does not exist here