# https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Pywikibot
import pywikibot
from pywikibot import pagegenerators
import requests

URL = ("http://data.libris.kb.se/open/auth/{}.rdf")
site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()
query = """SELECT ?item ?value
WHERE
{
?item wdt:P906 ?value .
}"""
generator = pagegenerators.WikidataSPARQLPageGenerator(query, site=repo)

for item in generator:
    item_dict = item.get()
    if not item_dict["sitelinks"].get("svwiki"):
        print(item_dict["labels"])
        selibr = item_dict['claims']['P906'][0].getTarget()
        print(selibr)
        url = URL.format(selibr)
        print(url)
        print("----------------------------")
{'de': 'Jorge Bucay', 'pl': 'Jorge Bucay', 'fa': 'خورخه بوکای', 'bg': 'Хорхе Букай', 'fr': 'Jorge Bucay', 'ru': 'Хорхе Букай', 'en': 'Jorge Bucay', 'es': 'Jorge Bucay', 'it': 'Jorge Bucay', 'nl': 'Jorge Bucay', 'nb': 'Jorge Bucay', 'da': 'Jorge Bucay', 'nn': 'Jorge Bucay', 'sv': 'Jorge Bucay', 'hy': 'Խորխե Բուկայ', 'sl': 'Jorge Bucay', 'el': 'Χόρχε Μπουκάι'}
348825
http://data.libris.kb.se/open/auth/348825.rdf
----------------------------
{'de': 'Kurt D. Singer', 'en': 'Kurt D. Singer', 'nl': 'Kurt D. Singer', 'fr': 'Kurt Singer', 'sl': 'Kurt D. Singer'}
315549
http://data.libris.kb.se/open/auth/315549.rdf
----------------------------
{'fr': 'Amaury du Closel', 'de': 'Amaury du Closel', 'nl': 'Amaury du Closel', 'en': 'Amaury Du Closel', 'es': 'Amaury Du Closel', 'hu': 'Amaury du Closel', 'sl': 'Amaury du Closel'}
369550
http://data.libris.kb.se/open/auth/369550.rdf
----------------------------
{'de': 'Andreas Reyher', 'fr': 'Andreas Reyher', 'nb': 'Andreas Reyher', 'da': 'Andreas Reyher', 'nn': 'Andreas Reyher', 'sv': 'Andreas Reyher', 'en': 'Andreas Reyher', 'es': 'Andreas Reyher', 'nl': 'Andreas Reyher', 'it': 'Andreas Reyher', 'sl': 'Andreas Reyher'}
318713
http://data.libris.kb.se/open/auth/318713.rdf
----------------------------
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/srv/paws/lib/python3.6/site-packages/urllib3/connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    379             try:  # Python 2.7, use buffering of HTTP responses
--> 380                 httplib_response = conn.getresponse(buffering=True)
    381             except TypeError:  # Python 2.6 and older, Python 3

TypeError: getresponse() got an unexpected keyword argument 'buffering'

During handling of the above exception, another exception occurred:

KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-14-f4969dce37f0> in <module>()
     15 
     16 for item in generator:
---> 17     item_dict = item.get()
     18     if not item_dict["sitelinks"].get("svwiki"):
     19         print(item_dict["labels"])

/srv/paws/pwb/pywikibot/page.py in get(self, force, get_redirect, *args, **kwargs)
   4277         @raise NotImplementedError: a value in args or kwargs
   4278         """
-> 4279         data = super(ItemPage, self).get(force, *args, **kwargs)
   4280 
   4281         if self.isRedirectPage() and not get_redirect:

/srv/paws/pwb/pywikibot/page.py in get(self, force, *args, **kwargs)
   3778 
   3779             try:
-> 3780                 data = self.repo.loadcontent(identification)
   3781             except APIError as err:
   3782                 if err.code == 'no-such-entity':

/srv/paws/pwb/pywikibot/site.py in loadcontent(self, identification, *props)
   7524                                     props=props if props else False)
   7525         req = self._simple_request(**params)
-> 7526         data = req.submit()
   7527         if 'success' not in data:
   7528             raise api.APIError(data['errors'])

/srv/paws/pwb/pywikibot/data/api.py in submit(self)
   1950                 rawdata = http.request(
   1951                     site=self.site, uri=uri, method='GET' if use_get else 'POST',
-> 1952                     body=body, headers=headers)
   1953             except Server504Error:
   1954                 pywikibot.log(u"Caught HTTP 504 error; retrying")

/srv/paws/pwb/pywikibot/tools/__init__.py in wrapper(*__args, **__kw)
   1519                              cls, depth)
   1520                     del __kw[old_arg]
-> 1521             return obj(*__args, **__kw)
   1522 
   1523         if not __debug__:

/srv/paws/pwb/pywikibot/comms/http.py in request(site, uri, method, params, body, headers, data, **kwargs)
    320     headers['user-agent'] = user_agent(site, format_string)
    321 
--> 322     r = fetch(baseuri, method, params, body, headers, **kwargs)
    323     return r.content
    324 

/srv/paws/pwb/pywikibot/comms/http.py in fetch(uri, method, params, body, headers, default_error_handling, use_fake_user_agent, data, **kwargs)
    515             headers['user-agent'] = fake_user_agent()
    516 
--> 517     request = _enqueue(uri, method, params, body, headers, **kwargs)
    518     assert(request._data is not None)  # if there's no data in the answer we're in trouble
    519     # Run the error handling callback in the callers thread so exceptions

/srv/paws/pwb/pywikibot/comms/http.py in _enqueue(uri, method, params, body, headers, data, **kwargs)
    472     request = threadedhttp.HttpRequest(
    473         uri, method, params, body, all_headers, callbacks, **kwargs)
--> 474     _http_process(session, request)
    475     return request
    476 

/srv/paws/pwb/pywikibot/comms/http.py in _http_process(session, http_request)
    386                                    headers=headers, auth=auth, timeout=timeout,
    387                                    verify=not ignore_validation,
--> 388                                    **http_request.kwargs)
    389     except Exception as e:
    390         http_request.data = e

/srv/paws/lib/python3.6/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    506         }
    507         send_kwargs.update(settings)
--> 508         resp = self.send(prep, **send_kwargs)
    509 
    510         return resp

/srv/paws/lib/python3.6/site-packages/requests/sessions.py in send(self, request, **kwargs)
    616 
    617         # Send the request
--> 618         r = adapter.send(request, **kwargs)
    619 
    620         # Total elapsed time of the request (approximately)

/srv/paws/lib/python3.6/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    438                     decode_content=False,
    439                     retries=self.max_retries,
--> 440                     timeout=timeout
    441                 )
    442 

/srv/paws/lib/python3.6/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    599                                                   timeout=timeout_obj,
    600                                                   body=body, headers=headers,
--> 601                                                   chunked=chunked)
    602 
    603             # If we're going to release the connection in ``finally:``, then

/srv/paws/lib/python3.6/site-packages/urllib3/connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    381             except TypeError:  # Python 2.6 and older, Python 3
    382                 try:
--> 383                     httplib_response = conn.getresponse()
    384                 except Exception as e:
    385                     # Remove the TypeError from the exception chain in Python 3;

/usr/lib/python3.6/http/client.py in getresponse(self)
   1329         try:
   1330             try:
-> 1331                 response.begin()
   1332             except ConnectionError:
   1333                 self.close()

/usr/lib/python3.6/http/client.py in begin(self)
    295         # read until we get a non-100 response
    296         while True:
--> 297             version, status, reason = self._read_status()
    298             if status != CONTINUE:
    299                 break

/usr/lib/python3.6/http/client.py in _read_status(self)
    256 
    257     def _read_status(self):
--> 258         line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
    259         if len(line) > _MAXLINE:
    260             raise LineTooLong("status line")

/usr/lib/python3.6/socket.py in readinto(self, b)
    584         while True:
    585             try:
--> 586                 return self._sock.recv_into(b)
    587             except timeout:
    588                 self._timeout_occurred = True

/usr/lib/python3.6/ssl.py in recv_into(self, buffer, nbytes, flags)
   1007                   "non-zero flags not allowed in calls to recv_into() on %s" %
   1008                   self.__class__)
-> 1009             return self.read(nbytes, buffer)
   1010         else:
   1011             return socket.recv_into(self, buffer, nbytes, flags)

/usr/lib/python3.6/ssl.py in read(self, len, buffer)
    869             raise ValueError("Read on closed or unwrapped SSL socket.")
    870         try:
--> 871             return self._sslobj.read(len, buffer)
    872         except SSLError as x:
    873             if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:

/usr/lib/python3.6/ssl.py in read(self, len, buffer)
    629         """
    630         if buffer is not None:
--> 631             v = self._sslobj.read(len, buffer)
    632         else:
    633             v = self._sslobj.read(len)

KeyboardInterrupt: