Back to Article
Notebook: Artwork
Download Notebook

Notebook: Artwork

A Juypter Notebook for retreiving artwork information from Wikidata item https://www.wikidata.org/wiki/Q141747732 | Exhibition title: while something is happening here, something else is happening there : works 1988 - 1999 (Exhibition).

Wikidata SPARQL query that looks for all P31 (instance of) that are Q838948 (work of art), and have P608 (exhibited history) Q141747732 (while something is happening here, exhibition)

SPARQL Query in Wikidata: https://w.wiki/czh4

BELOW!

```lSELECT ?artwork ?artworkLabel WHERE { # Artwork is an instance of “work of art” (Q838948) ?artwork wdt:P31 wd:Q838948 ; # Has exhibition history (P608) pointing to the exhibition (Q141747732) wdt:P608 wd:Q141747732 .

# Fetch human-readable labels (defaults to user language, then English) SERVICE wikibase:label { bd:serviceParam wikibase:language “[AUTO_LANGUAGE],en”. } } LIMIT 100```

In [34]:
Show code
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from IPython.display import HTML, display
import json

query = """
SELECT ?artwork ?artworkLabel WHERE {
  # Artwork is an instance of "work of art" (Q838948)
  ?artwork wdt:P31 wd:Q838948 ;
           # Has exhibition history (P608) pointing to the exhibition (Q141747732)
           wdt:P608 wd:Q141747732 .

  # Fetch human-readable labels (defaults to user language, then English)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
LIMIT 100
"""

endpoint = "https://query.wikidata.org/sparql"
params = urlencode({"query": query, "format": "json"})
url = f"{endpoint}?{params}"

request = Request(
    url,
    headers={
        "Accept": "application/sparql-results+json",
        "User-Agent": "loe-posit-notebook/1.0 (contact: simon.worthington@tib.eu)",
    },
)

with urlopen(request, timeout=60) as response:
    data = json.loads(response.read().decode("utf-8"))

rows = []
for b in data["results"]["bindings"]:
    rows.append(
        {
            "artwork_id": b["artwork"]["value"].rsplit("/", 1)[-1],
            "artwork": b.get("artworkLabel", {}).get("value", b["artwork"]["value"]),
        }
    )

if not rows:
    print("No artworks found for this exhibition.")
else:
    headers = ["artwork_id", "artwork"]
    table = [
        "<table><thead><tr>" + "".join(f"<th>{h}</th>" for h in headers) + "</tr></thead><tbody>",
    ]
    for row in rows:
        table.append(
            "<tr>" + "".join(f"<td>{row.get(h, '')}</td>" for h in headers) + "</tr>"
        )
    table.append("</tbody></table>")
    display(HTML("".join(table)))
artwork_id artwork
Q141749370 Duck Pond Bar, National City, California
Q141757299 The Former Site Of Duck Pond Bar, 3003 National City Blvd., National City California