Skip to content

Instantly share code, notes, and snippets.

@mbabaian
Created January 30, 2018 19:41
Show Gist options
  • Save mbabaian/52937761cdfbeeb4ef866d51fac60635 to your computer and use it in GitHub Desktop.
Save mbabaian/52937761cdfbeeb4ef866d51fac60635 to your computer and use it in GitHub Desktop.
The python program only publishes the first item in the query. I'd like to iterate through all items and publish them to HTML but can't figure out how.
# Practicing call to DPLA and getting data from it, then displaying results via html
import webbrowser
from operator import itemgetter
import requests
f=open('result.html', 'w')
# Make an api call and store the response.
url = "https://api.dp.la/v2/items?q=penguins&api_key=aefc7b2874411888e4e06b515935c19c"
r = requests.get(url)
print('Status code: ', r.status_code)
# Process information from each item
data = r.json()
data_list = []
for d in data['docs']:
# print('Title:', d['sourceResource']['title'])
# print('Source:', d['dataProvider'])
# print('URL:', d['isShownAt'])
title = d['sourceResource']['title']
source =d['dataProvider']
link = d['isShownAt']
data_list.append(d)
# iterate through data_list and add each item to html
for item in data_list:
message = """<html>
<head>
<title> Practice </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"></link>
<style>
body { margin-top: 20px; margin-left: 20px;}
h1 { }
</style>
</head>
<body>
<h1> Practicing Python Queries to HTML Data </h1>
<p><strong>Title: </strong><a href="%s"> %s</a><br><strong>Location: </strong>%s</p>
</body>
</html>"""
# pass results from python query to html display
result = message % (link, title, source)
# write all data to html file
f.write(result)
f.close()
webbrowser.open_new_tab('result.html')
<!-- This is the html file created from the above python file -->
<html>
<head>
<title> Practice </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"></link>
<style>
body { margin-top: 20px; margin-left: 20px;}
h1 { }
</style>
</head>
<body>
<h1> Practicing Python Queries to HTML Data </h1>
<p><strong>Title: </strong><a href="http://digitalcollections.nypl.org/items/510d47db-dcac-a3d9-e040-e00a18064a99"> Poems for penguins</a><br><strong>Location: </strong>General Research Division. The New York Public Library</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment