5. Web Scraping Using BeautifulSoup#

5.2. How Websites Prevent You From Scraping#

This discussion follows the excellent overview by a Stack Overflow and GitHub contributor with the username JonasCz (I wish I knew this user’s real name!) on how to prevent web scraping.

To understand the restrictions and challenges you will encounter when scraping data, put yourself in the position of a website’s owner:

If you own and maintain a website, there are many reasons why you might want to prevent web scraping bots from accessing the data on your website. Maybe the bots will overload the traffic to your site and make it impossible for your website to work as you intend. You might be running a business through this website and sharing the data in mass transfers would undercut your business. For whatever reason, you are now faced with a challenge: how to you prevent automated scraping of the data on your webpage while still allowing individual customers to view your website?

Web scraping will require issuing HTTP requests to a particular web address with a tool like requests, sometimes many times in a short period. Every HTTP request is logged by the server that receives the request, and these logs contain the IP address of the entity making the request. If too many requests are made by the same IP address, the server can block that IP address. The coding logic to automatically identify and block overactive IP addresses is simple, so many websites include these security measures. Some blocks are temporary, placing a rate limit on these requests to slow down the scrapers, and some blocks reroute scrapers through a CAPTCHA (which stands for “Completely Automated Test to Tell Computers and Humans Apart”) to prevent robots like a scraper from accessing the website. JonasCz recommends that these security measures look at other factors as well: the speed of actions on the website, the amount of data requested, and other factors that can identify a user when the IP address is masked.

Stronger gates, such as making users register for a username and password with email confirmation to use your website, are effective against scraping bots. But they also turn away individuals who wouldn’t want to jump through those hoops. Saving all text as images on your server will prevent bots from accessing the text very easily, but it makes the website harder to use and violates regulations that protect people with disabilities.

Instead, JonasCz recommends building your website in a way that never reveals the entirety of the data you own, and never reveals the private API endpoints you use to display the data. Also, web scrapers are fragile: they are built to pull data from the specific HTML structure of a particular website. Changing the HTML code frequently or using different versions of the code based on geographic location will break the scrapers that are built for that code. JonasCz also suggests adding “honeypot” links to the HTML code that will not be displayed to legitimate users but will be followed by scrapers that recursively follow links, and taking action against the agents that follow these links: block their IP addresses, require a CAPTCHA, or deliver fake data.

One important piece of information in a request is the user agent header (which we discuss in more detail below). JonasCz recommends looking at this information and blocking requests when the user agent is blank or matches information from agents that have previously been identified as malicious bots.

Understanding the steps you would take to protect your data from bots if you owned a website, you should have greater insight into why a web scraping endeavor may fail. Your web scraper might not be malicious, but might still violate the rules that the website owner setup to guard against bots. These rules are usually listed explicitly in a file on the server, usually called robots.txt. Some tips for reading and understanding a robots.txt file are here: https://www.promptcloud.com/blog/how-to-read-and-respect-robots-file/

For example, in this document we will be scraping data on the playlist of a radio station from https://spinitron.com/. This website has a robots.txt file here: https://spinitron.com/robots.txt, which reads:

User-agent: *
Crawl-delay: 10
Request-rate: 1/10

The User-agent: * line tells us that the next two lines apply to all user agent strings. Crawl-delay: 10 places a limit on the frequency with which our scraper can make a request from this website. In this case, individual requests must be made 10 second apart. Request-rate: 1/10 tells us that our scraper is only allowed to access one page every 10 seconds, and that we are not allowed to make requests from more than one page at the same time.

5.3. Using requests with a User Agent Header#

As the articles by James Densmore and JonasCz described, requests are much more likely to get blocked by websites if the request does not specify a header that contains a user agent. An HTTP header is a parameter that gets sent along with the HTTP request that contains metadata about the request. A user agent header contains contact and identification information about the person making the request. If there is any issue with your web scraper, you want to give the website owner a chance to contact you directly about that problem. If you do not feel comfortable being contacted by the website’s owner, you should reconsider whether you should be scraping that website.

Fortunately, it is straightforward to include headers in a GET request using requests: just use the headers argument. First, we import the relevant libraries:

import numpy as np
import pandas as pd
import requests

In module 4 we issued GET requests from the Wikipedia API as an example.

r = requests.get("https://en.wikipedia.org/w/api.php")
r
<Response [200]>

To add a user agent string, I use the following code:

headers = {'user-agent': 'Kropko class example (jkropko@virginia.edu)'}
r = requests.get("https://en.wikipedia.org/w/api.php", headers = headers)
r
<Response [200]>

What information needs to go into a user agent header? Different resources have different information about that. According to Amazon Web Services, a user agent should identify your application, its version number, and programming language. So a user agent should look like this:

headers = {'user-agent': 'Kropko class example version 1.0 (jkropko@virginia.edu) (Language=Python 3.8.2; Platform=Mac OSX 10.15.5)'}
r = requests.get("https://en.wikipedia.org/w/api.php", headers = headers)
r
<Response [200]>

Including a user agent is not hard, and it goes a long way towards alleviating the anxieties that website owners have about dealing with your web scraping code. It is a good practice to cultivate into a habit.

5.4. Using BeautifulSoup() (Example: WNRN, Charlottesville’s Legendary Radio Station)#

WNRN is a legendary radio station, and it’s based right here in Charlottesville at 91.9 FM (and streaming online at www.wnrn.org). It’s commercial-free, with only a few interruptions for local nonprofits to tell you about cool things happening in town. They play a mix of new and classic alternative rock and R&B. They emphasize music for bands coming to play at local venues. And they play the Grateful Dead on Saturday mornings. You should be listening to WNRN!

The playlist of the songs that WNRN has played in the last few hours is here: https://spinitron.com/WNRN/. I want to scrape the data off this website. I also want to scrape the data off of the additional playlists that this website links to, to collect as much data as possible. Our goal in this example is to create a dataframe of each song WNRN has played, the artist, the album, and the time each song was played.

The process involves four steps:

  1. Download the raw text of the HTML code for the website we want to scrape using the requests library.

  2. Use the BeautifulSoup() function from the bs4 library to parse the raw text so that Python can understand, search through, and operate on the HTML tags from string.

  3. Use methods associated with BeautifulSoup() to extract the data we need from the HTML code.

  4. Place the data into a pandas data frame.

5.4.1. Downloading and Understanding Raw HTML#

For this example, I first download the HTML that exists on https://spinitron.com/WNRN using the requests.get() function. To be ethical and to help this website’s owners know that I am not a malicious actor, I also specify a user agent string.

url = "https://spinitron.com/WNRN"
headers = {'user-agent': 'Kropko class example (jkropko@virginia.edu)'}
r = requests.get(url, headers=headers)
r
<Response [200]>

The raw HTML code contains a series of text fragments that look like this,

<tag attribute="value"> Navigable string </tag>

where tag, attribute, "value", and Navigable string are replaced by specific parameters and data that control the content and presentation of the webpage that gets displayed in a web browser. For example, here are the first 1000 characters of the raw text from WNRN’s playlist:

print(r.text[0:1000])
<!doctype html><html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1">
    <title>WNRN – Independent Music Radio</title>
    <meta name="description" content="A member-supported, independent music radio station broadcasting from the Blue Ridge to the Bay across Virginia—Richmond, Hampton Roads, Roanoke, Charlottesville, Lynchburg, Nelson County, Williamsburg, and The Shenandoah Valley.">

                                    <meta name="csrf-param" content="_csrf">
<meta name="csrf-token" content="XY-IUzxJJ7gmqsy-G2umwNl1bKjol-wHmMey_ThUMFM1_MIgWxtz9WXwu81WRouftTAI0pGgvGKpkfyxfC1Uag==">

    <meta property="og:url" content="/WNRN/">
<meta property="og:title" content="WNRN – Independent Music Radio">
<meta property="og:description" content="A member-supported, independent music radio station broadcasting from the Blue Ridge to the Bay across Virgi

Tags specify how the data contained within the page are organized and how the visual elements on this page should look. Tags are designated by opening and closing angle braces, < and >. In the HTML code displayed above, there are tags named

  • <html>, which tells browsers that the following code is written in HTML,

  • <meta>, which defines metadata in the document that help govern how the output shold be displayed in the browser,

  • <title>, which sets the title of the document, and

  • <link>, which pulls data or images from external resources for later use.

To see what other HTML tags do, look at the list on https://www.w3schools.com/TAGs/.

In some cases the tag operates on the text that immediately follows, and a closing tag </tag> frames the text that gets operated on by the tag. The text in between the opening and closing tag is called the navigable string. For example, the tag <title>WNRN Independent Music Radio</title> specifies that “WNRN – Independent Music Radio”, and only this string, is the title.

Some tags have attributes, which are arguments listed inside an opening tag to modify the behavior of that tag or to attach relevant data to the tag. The first <html> tag listed above contains an attribute lang with a value "en" that specifies that this document contains HTML code in English.

5.4.2. Parsing Raw HTML Using BeautifulSoup()#

The requests.get() function only downloads the raw text of the HTML code, but it does not yet understand the logic and organization of the HTML code. Getting Python to register text as a particular coding standard is called parsing the code. We’ve parsed code into Python before with JSON data. We used requests.get() to download the JSON formatted data, but we needed json.loads() to parse the data in order to be able to navigate the branches of the JSON tree.

There are two widely used Python libraries for parsing HTML data: bs4 which contains the BeautifulSoup() function, and selenium. BeautifulSoup() works with raw text, but cannot access websites themselves (we use requests.get() for that). In order to access the data on a website, the data needs to be visible in the raw HTML that requests.get() returns. If there are measures taken by a website to hide that data, possibly by calling server-side Javascript to populate data fields, or by saving data as image files, then we won’t be able to access the data with an HTML parser. selenium has more features to extract more complicated data and circumvent anti-scraping measures, such as taking a screenshot of the webpage in a browser and using optical character recognition (OCR) to pull data directly from the image. However, selenium requires each request to be loaded in a web browser, so it can be quite a bit slower than BeautifulSoup(). If you are interested in learning how to use selenium, see this guide: https://selenium-python.readthedocs.io/. Here we will be using BeautifulSoup().

First I import the BeautifulSoup() function:

from bs4 import BeautifulSoup

To use it, we pass the .text attribute of the requests.get() output from https://spinitron.com/WNRN to BeautifulSoup() (which I saved as r.text above). This function can parse either HTML or XML code, so the second argument should specify HTML:

wnrn = BeautifulSoup(r.text, 'html')

Now that the https://spinitron.com/WNRN source code is registered as HTML code in Python, we can begin executing commands to navigate the organizational structure of the code and extract data.

5.4.3. Searching for HTML Tags and Extracting Data#

While HTML is a coding language, it does not force coders to follow very strict templates. There’s a lot of flexibility and creativity possible for HTML programmers, and as such, there is no one universal method for extracting data from HTML. The best approach is to open a browser window, navigate to the webpage you want to scrape, and “view page source”. (Different web browsers have different ways to do that. On Mozilla Firefox, right click somewhere on the page other than an active link, and “view page source” should be an option.) The source will display the raw HTML code that generates the page. You will need to search through this code to find examples of the data points you intend to collect, possibly using control+F to search for specific values. Once you find the data you need, make note of the tags that surround the data and use the tools we will describe next to extract the data.

The parsable HTML BeautifulSoup() output, wnrn, has important methods and attributes that we will use to extract the data we want. First, we can use the name of a tag as an attribute to extract the first occurrence of that tag. Here we extract the first <meta> tag:

metatag = wnrn.meta
metatag
<meta charset="utf-8"/>

This tag stores its attributes as a list, so we can extract the value of an attribute by calling the name of that attribute as follows:

metatag['charset']
'utf-8'

If a tag has a navigable string, we can extract that with the .string attribute of a particular tag. For example, to extract the title, we start with the <title> tag:

titletag = wnrn.title
titletag
<title>WNRN – Independent Music Radio</title>

Then we extract the title as follows:

titletag.string
'WNRN – Independent Music Radio'

Our goal in this example is to extract the artist, song, album, and time played for every song played on WNRN. I look in the raw HTML source code for the first instance of an artist. These data are contained in the <span> tags:

spantag = wnrn.span
spantag
<span class="artist">Baby Rose f/ BADBADNOTGOOD</span>

Calling one tag is not especially useful, because we generally want to extract all of the relevant data on a page. For that, we can use the .find_next() and .find_all() methods, both of which are very literal. The next <span> tag in the HTML code contains the song associated with the artist:

spantag.find_next()
<span class="song">Weekness</span>

And the next occurrence of <span> contains the album name (under "release"):

spantag.find_next().find_next()
<div class="info"><span class="release">Slow Burn EP</span></div>

To find all occurrences of the <span> tag, organized in a list, use .find_all() and provide the tag as the argument:

spanlist = wnrn.find_all("span")
spanlist
[<span class="artist">Baby Rose f/ BADBADNOTGOOD</span>,
 <span class="song">Weekness</span>,
 <span class="release">Slow Burn EP</span>,
 <span class="artist">Angie McMahon</span>,
 <span class="song">Untangling</span>,
 <span class="release">Light Sides EP</span>,
 <span class="artist">Willie Nelson and Daniel Lanois</span>,
 <span class="song">The Maker</span>,
 <span class="release">Teatro</span>,
 <span class="artist">Lucy Dacus</span>,
 <span class="song">Ankles</span>,
 <span class="release">Forever Is A Feeling</span>,
 <span class="artist">Brigitte Calls Me Baby</span>,
 <span class="song">Too Easy</span>,
 <span class="release">The Future Is Our Way Out</span>,
 <span class="artist">Kashus Culpepper</span>,
 <span class="song">After Me?</span>,
 <span class="release">(Single)</span>,
 <span class="artist">Deep Sea Diver</span>,
 <span class="song">Shovel</span>,
 <span class="release">Billboard Heart</span>,
 <span class="artist">The Devil Makes Three</span>,
 <span class="song">Spirits</span>,
 <span class="release">Spirits</span>,
 <span class="artist">The Barons</span>,
 <span class="song">Would You Want It (If You Had It)</span>,
 <span class="release">(Single)</span>,
 <span class="artist">Sunflower Bean</span>,
 <span class="song">Champagne Taste</span>,
 <span class="release">Mortal Primetime</span>,
 <span class="artist">Ray LaMontagne</span>,
 <span class="song">And They Call Her California</span>,
 <span class="release">Long Way Home</span>,
 <span class="artist">Spoon</span>,
 <span class="song">The Underdog</span>,
 <span class="release">Ga Ga Ga Ga Ga</span>,
 <span class="artist">Noeline Hofmann</span>,
 <span class="song">Lightning in July (Prairie Fire)</span>,
 <span class="release">Purple Gas</span>,
 <span class="artist">Inhaler</span>,
 <span class="song">Your House</span>,
 <span class="release">Open Wide</span>,
 <span class="artist">John Prine</span>,
 <span class="song">Lake Marie</span>,
 <span class="release">Lost Dogs &amp; Mixed Blessings</span>,
 <span class="artist">49 Winchester</span>,
 <span class="song">Miles to Go</span>,
 <span class="release">(Single)</span>,
 <span class="artist">Ruthie Foster</span>,
 <span class="song">Rainbow</span>,
 <span class="release">Mileage</span>,
 <span class="artist">Joy Oladokun</span>,
 <span class="song">DUST/DIVINITY</span>,
 <span class="release">Observations From A Crowded Room</span>,
 <span class="artist">Death Cab for Cutie</span>,
 <span class="song">Cath</span>,
 <span class="release">Narrow Stairs</span>,
 <span class="artist">Jeremie Albino</span>,
 <span class="song">Rolling Down the 405</span>,
 <span class="release">Our Time In The Sun</span>,
 <span class="artist">Cristina Vane f/ Molly Tuttle</span>,
 <span class="song">Hear My Call</span>,
 <span class="release">Hear My Call</span>,
 <span class="artist">Ziggy Marley &amp; the Melody Makers</span>,
 <span class="song">Tomorrow People</span>,
 <span class="release">Conscious Party</span>,
 <span class="artist">Chuck Prophet</span>,
 <span class="song">First Came The Thunder</span>,
 <span class="release">Wake the Dead</span>,
 <span class="artist">The Vices</span>,
 <span class="song">Before It Might Be Gone</span>,
 <span class="release">Before It Might Be Gone</span>,
 <span class="artist">Jim Lauderdale</span>,
 <span class="song">Don't Leave Your Light Low</span>,
 <span class="release">Persimmons</span>,
 <span class="artist">Humbird</span>,
 <span class="song">Blueberry Bog</span>,
 <span class="release">Right On</span>,
 <span class="artist">ALO</span>,
 <span class="song">Blank Canvas</span>,
 <span class="release">Frames</span>,
 <span class="artist">Tracy Chapman</span>,
 <span class="song">You're the One</span>,
 <span class="release">Let It Rain</span>,
 <span class="artist">The Bamboos</span>,
 <span class="song">Hard Up</span>,
 <span class="release">Hard Up</span>,
 <span class="artist">Oracle Sisters</span>,
 <span class="song">Alouette</span>,
 <span class="release">Divinations</span>,
 <span class="artist">Ruthie Foster</span>,
 <span class="song">Singing the Blues</span>,
 <span class="release">Promise of a Brand New Day</span>,
 <span class="artist">Local The Neighbour</span>,
 <span class="song">Cruise Control</span>,
 <span class="release">VALLEY pt. 2</span>,
 <span class="artist">Kasey Chambers</span>,
 <span class="song">Broken Cup</span>,
 <span class="release">Backbone</span>,
 <span class="artist">Hiss Golden Messenger</span>,
 <span class="song">Heart like a Levee</span>,
 <span class="release">Heart Like a Levee</span>,
 <span class="artist">Daughter of Swords</span>,
 <span class="song">Alone Together</span>,
 <span class="release">Cardinals At The Window</span>,
 <span class="artist">Soccer Mommy</span>,
 <span class="song">Circle the Drain</span>,
 <span class="release">Color Theory</span>,
 <span class="artist">Pug Johnson</span>,
 <span class="song">Believer</span>,
 <span class="release">El Cabron</span>,
 <span class="artist">JD McPherson</span>,
 <span class="song">I Can't Go Anywhere With You</span>,
 <span class="release">Nite Owls</span>,
 <span class="artist">Guster</span>,
 <span class="song">Amsterdam</span>,
 <span class="release">Keep It Together</span>,
 <span class="artist">Jungle</span>,
 <span class="song">Keep Me Satisfied</span>,
 <span class="release">(Single)</span>,
 <span class="artist">Johnny Delaware</span>,
 <span class="song">Running</span>,
 <span class="release">Para Llevar</span>,
 <span class="artist">Nickel Creek</span>,
 <span class="song">This Side</span>,
 <span class="release">This Side</span>,
 <span class="artist">Luke Winslow-King</span>,
 <span class="song">Flash-A-Magic</span>,
 <span class="release">Flash-A-Magic</span>,
 <span class="artist">The English Beat</span>,
 <span class="song">Best Friend</span>,
 <span class="release">I Just Can't Stop It</span>,
 <span class="artist">Bebe Stockwell</span>,
 <span class="song">Minor Inconveniences</span>,
 <span class="release">(Single)</span>,
 <span class="artist">Wallice</span>,
 <span class="song">I Want You Yesterday</span>,
 <span class="release">The Jester</span>,
 <span class="artist">Jesper Lindell</span>,
 <span class="song">One of These Rainy Days</span>,
 <span class="release">Before the Sun</span>,
 <span class="artist">The Smile</span>,
 <span class="song">No Words</span>,
 <span class="release">Cutouts</span>,
 <span class="artist">Mumford &amp; Sons</span>,
 <span class="song">Rushmere</span>,
 <span class="release">Rushmere</span>,
 <span class="artist">Ray Charles</span>,
 <span class="song">What'd I Say Pts I and II</span>,
 <span class="release">What'd I Say</span>,
 <span class="artist">Kat Edmonson</span>,
 <span class="song">Keep Movin'</span>,
 <span class="release">Keep Movin'</span>,
 <span class="artist">The Heavy Heavy</span>,
 <span class="song">Feel</span>,
 <span class="release">One of a Kind</span>,
 <span class="artist">Waxahatchee</span>,
 <span class="song">Can't Do Much</span>,
 <span class="release">Saint Cloud</span>,
 <span class="artist">Johnny Blue Skies</span>,
 <span class="song">If The Sun Never Rises Again</span>,
 <span class="release">Passage Du Desir</span>,
 <span class="artist">Charley Crockett</span>,
 <span class="song">Lonesome Drifter</span>,
 <span class="release">Lonesome Drifter</span>,
 <span class="artist">Morrissey</span>,
 <span class="song">Suedehead</span>,
 <span class="release">Viva Hate</span>]

Notice that the HTML source code distinguishes between the three types of datapoint with different class values. To limit this list to just the artists, we can specify the "artist" class as a second argument of .find_all():

artistlist = wnrn.find_all("span", "artist")
artistlist
[<span class="artist">Baby Rose f/ BADBADNOTGOOD</span>,
 <span class="artist">Angie McMahon</span>,
 <span class="artist">Willie Nelson and Daniel Lanois</span>,
 <span class="artist">Lucy Dacus</span>,
 <span class="artist">Brigitte Calls Me Baby</span>,
 <span class="artist">Kashus Culpepper</span>,
 <span class="artist">Deep Sea Diver</span>,
 <span class="artist">The Devil Makes Three</span>,
 <span class="artist">The Barons</span>,
 <span class="artist">Sunflower Bean</span>,
 <span class="artist">Ray LaMontagne</span>,
 <span class="artist">Spoon</span>,
 <span class="artist">Noeline Hofmann</span>,
 <span class="artist">Inhaler</span>,
 <span class="artist">John Prine</span>,
 <span class="artist">49 Winchester</span>,
 <span class="artist">Ruthie Foster</span>,
 <span class="artist">Joy Oladokun</span>,
 <span class="artist">Death Cab for Cutie</span>,
 <span class="artist">Jeremie Albino</span>,
 <span class="artist">Cristina Vane f/ Molly Tuttle</span>,
 <span class="artist">Ziggy Marley &amp; the Melody Makers</span>,
 <span class="artist">Chuck Prophet</span>,
 <span class="artist">The Vices</span>,
 <span class="artist">Jim Lauderdale</span>,
 <span class="artist">Humbird</span>,
 <span class="artist">ALO</span>,
 <span class="artist">Tracy Chapman</span>,
 <span class="artist">The Bamboos</span>,
 <span class="artist">Oracle Sisters</span>,
 <span class="artist">Ruthie Foster</span>,
 <span class="artist">Local The Neighbour</span>,
 <span class="artist">Kasey Chambers</span>,
 <span class="artist">Hiss Golden Messenger</span>,
 <span class="artist">Daughter of Swords</span>,
 <span class="artist">Soccer Mommy</span>,
 <span class="artist">Pug Johnson</span>,
 <span class="artist">JD McPherson</span>,
 <span class="artist">Guster</span>,
 <span class="artist">Jungle</span>,
 <span class="artist">Johnny Delaware</span>,
 <span class="artist">Nickel Creek</span>,
 <span class="artist">Luke Winslow-King</span>,
 <span class="artist">The English Beat</span>,
 <span class="artist">Bebe Stockwell</span>,
 <span class="artist">Wallice</span>,
 <span class="artist">Jesper Lindell</span>,
 <span class="artist">The Smile</span>,
 <span class="artist">Mumford &amp; Sons</span>,
 <span class="artist">Ray Charles</span>,
 <span class="artist">Kat Edmonson</span>,
 <span class="artist">The Heavy Heavy</span>,
 <span class="artist">Waxahatchee</span>,
 <span class="artist">Johnny Blue Skies</span>,
 <span class="artist">Charley Crockett</span>,
 <span class="artist">Morrissey</span>]

Likewise we can create lists of the songs:

songlist = wnrn.find_all("span", "song")
songlist
[<span class="song">Weekness</span>,
 <span class="song">Untangling</span>,
 <span class="song">The Maker</span>,
 <span class="song">Ankles</span>,
 <span class="song">Too Easy</span>,
 <span class="song">After Me?</span>,
 <span class="song">Shovel</span>,
 <span class="song">Spirits</span>,
 <span class="song">Would You Want It (If You Had It)</span>,
 <span class="song">Champagne Taste</span>,
 <span class="song">And They Call Her California</span>,
 <span class="song">The Underdog</span>,
 <span class="song">Lightning in July (Prairie Fire)</span>,
 <span class="song">Your House</span>,
 <span class="song">Lake Marie</span>,
 <span class="song">Miles to Go</span>,
 <span class="song">Rainbow</span>,
 <span class="song">DUST/DIVINITY</span>,
 <span class="song">Cath</span>,
 <span class="song">Rolling Down the 405</span>,
 <span class="song">Hear My Call</span>,
 <span class="song">Tomorrow People</span>,
 <span class="song">First Came The Thunder</span>,
 <span class="song">Before It Might Be Gone</span>,
 <span class="song">Don't Leave Your Light Low</span>,
 <span class="song">Blueberry Bog</span>,
 <span class="song">Blank Canvas</span>,
 <span class="song">You're the One</span>,
 <span class="song">Hard Up</span>,
 <span class="song">Alouette</span>,
 <span class="song">Singing the Blues</span>,
 <span class="song">Cruise Control</span>,
 <span class="song">Broken Cup</span>,
 <span class="song">Heart like a Levee</span>,
 <span class="song">Alone Together</span>,
 <span class="song">Circle the Drain</span>,
 <span class="song">Believer</span>,
 <span class="song">I Can't Go Anywhere With You</span>,
 <span class="song">Amsterdam</span>,
 <span class="song">Keep Me Satisfied</span>,
 <span class="song">Running</span>,
 <span class="song">This Side</span>,
 <span class="song">Flash-A-Magic</span>,
 <span class="song">Best Friend</span>,
 <span class="song">Minor Inconveniences</span>,
 <span class="song">I Want You Yesterday</span>,
 <span class="song">One of These Rainy Days</span>,
 <span class="song">No Words</span>,
 <span class="song">Rushmere</span>,
 <span class="song">What'd I Say Pts I and II</span>,
 <span class="song">Keep Movin'</span>,
 <span class="song">Feel</span>,
 <span class="song">Can't Do Much</span>,
 <span class="song">If The Sun Never Rises Again</span>,
 <span class="song">Lonesome Drifter</span>,
 <span class="song">Suedehead</span>]

And a list for the albums:

albumlist = wnrn.find_all("span", "release")
albumlist
[<span class="release">Slow Burn EP</span>,
 <span class="release">Light Sides EP</span>,
 <span class="release">Teatro</span>,
 <span class="release">Forever Is A Feeling</span>,
 <span class="release">The Future Is Our Way Out</span>,
 <span class="release">(Single)</span>,
 <span class="release">Billboard Heart</span>,
 <span class="release">Spirits</span>,
 <span class="release">(Single)</span>,
 <span class="release">Mortal Primetime</span>,
 <span class="release">Long Way Home</span>,
 <span class="release">Ga Ga Ga Ga Ga</span>,
 <span class="release">Purple Gas</span>,
 <span class="release">Open Wide</span>,
 <span class="release">Lost Dogs &amp; Mixed Blessings</span>,
 <span class="release">(Single)</span>,
 <span class="release">Mileage</span>,
 <span class="release">Observations From A Crowded Room</span>,
 <span class="release">Narrow Stairs</span>,
 <span class="release">Our Time In The Sun</span>,
 <span class="release">Hear My Call</span>,
 <span class="release">Conscious Party</span>,
 <span class="release">Wake the Dead</span>,
 <span class="release">Before It Might Be Gone</span>,
 <span class="release">Persimmons</span>,
 <span class="release">Right On</span>,
 <span class="release">Frames</span>,
 <span class="release">Let It Rain</span>,
 <span class="release">Hard Up</span>,
 <span class="release">Divinations</span>,
 <span class="release">Promise of a Brand New Day</span>,
 <span class="release">VALLEY pt. 2</span>,
 <span class="release">Backbone</span>,
 <span class="release">Heart Like a Levee</span>,
 <span class="release">Cardinals At The Window</span>,
 <span class="release">Color Theory</span>,
 <span class="release">El Cabron</span>,
 <span class="release">Nite Owls</span>,
 <span class="release">Keep It Together</span>,
 <span class="release">(Single)</span>,
 <span class="release">Para Llevar</span>,
 <span class="release">This Side</span>,
 <span class="release">Flash-A-Magic</span>,
 <span class="release">I Just Can't Stop It</span>,
 <span class="release">(Single)</span>,
 <span class="release">The Jester</span>,
 <span class="release">Before the Sun</span>,
 <span class="release">Cutouts</span>,
 <span class="release">Rushmere</span>,
 <span class="release">What'd I Say</span>,
 <span class="release">Keep Movin'</span>,
 <span class="release">One of a Kind</span>,
 <span class="release">Saint Cloud</span>,
 <span class="release">Passage Du Desir</span>,
 <span class="release">Lonesome Drifter</span>,
 <span class="release">Viva Hate</span>]

Finally, we want to also extract the times each song was played. I look at the HTML code and find an example of the play time. These times are stored in the <td> tag with class="spin-time". I create a list of these times:

timelist = wnrn.find_all("td", "spin-time")
timelist
[<td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404900332">10:01 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404900043">9:57 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404899761">9:52 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404899574">9:49 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404899290">9:44 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404899108">9:41 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404898822">9:37 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404898449">9:31 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404898231">9:27 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404898035">9:24 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404897743">9:18 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404897461">9:14 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404897244">9:10 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404896934">9:04 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404896543">8:59 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404896311">8:55 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404896139">8:51 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404895788">8:45 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404895496">8:41 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404895300">8:38 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404894901">8:31 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404894703">8:27 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404894280">8:19 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404894034">8:15 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404893873">8:11 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404893736">8:09 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404893382">8:03 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404893206">8:00 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404892835">7:55 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404892629">7:52 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404892405">7:48 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404892087">7:43 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404891894">7:39 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404891665">7:35 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404891511">7:33 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404890936">7:22 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404890703">7:18 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404890440">7:14 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404890225">7:10 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404890090">7:07 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404889741">7:02 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404889447">6:58 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404889226">6:55 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404889050">6:52 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404888886">6:49 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404888635">6:45 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404888433">6:42 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404888131">6:37 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404887816">6:32 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404887419">6:25 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404887228">6:22 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404886918">6:17 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404886706">6:13 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404886427">6:09 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404886148">6:04 AM</a></td>,
 <td class="spin-time"><a href="/WNRN/pl/20207938/WNRN?sp=404885903">6:00 AM</a></td>]

Sometimes the information we need exists in a particular tag, but only when a specific attribute is present. For example, in the WNRN playlist HTML there are many <a> tags, but only some of those tags include a title attribute. To extract all of the <a> tags with a title attribute, specify title=True in the call to .find_all():

atags_title = wnrn.find_all("a", title=True)
print(atags_title[0:5]) # just show the first 6 elements
[<a class="buy-link" data-vendor="apple" href="#" target="_blank" title='View "Baby Rose f/ BADBADNOTGOOD - Weekness" on Apple'><div alt='View "Baby Rose f/ BADBADNOTGOOD - Weekness" on Apple' class="buy-icon buy-icon-apple"></div></a>, <a class="buy-link" data-vendor="amazon" href="#" target="_blank" title='View "Baby Rose f/ BADBADNOTGOOD - Weekness" on Amazon'><div alt='View "Baby Rose f/ BADBADNOTGOOD - Weekness" on Amazon' class="buy-icon buy-icon-amazon"></div></a>, <a class="buy-link" data-vendor="spotify" href="#" target="_blank" title='View "Baby Rose f/ BADBADNOTGOOD - Weekness" on Spotify'><div alt='View "Baby Rose f/ BADBADNOTGOOD - Weekness" on Spotify' class="buy-icon buy-icon-spotify"></div></a>, <a class="buy-link" data-vendor="apple" href="#" target="_blank" title='View "Angie McMahon - Untangling" on Apple'><div alt='View "Angie McMahon - Untangling" on Apple' class="buy-icon buy-icon-apple"></div></a>, <a class="buy-link" data-vendor="amazon" href="#" target="_blank" title='View "Angie McMahon - Untangling" on Amazon'><div alt='View "Angie McMahon - Untangling" on Amazon' class="buy-icon buy-icon-amazon"></div></a>]

5.4.4. Constructing a Data Frame from HTML Data#

Next we need to place these data into a clean data frame. For that, we will need to keep the valid data while dropping the HTML tags. We stored the tags with the artists, songs, albums, and times in separate lists. Every name is stored as a navigable string in the HTML tags, so to extract these names we need to loop across the elements of the list. The simplest loop for this task is called a list comprehension, which has the following syntax:

newlist = [ expression for item in oldlist if condition ]

In this syntax, we are creating a new list by iteratively performing operations on the elements of an existing list (oldlist). item is a token that we will use to represent one item of the existing list. expression is the same Python code we would use on a single element of the existing list, except we replace the name of the element with the token defined with item. Finally condition is an optional part of this code which sets a filter by which only certain elements of the old list are transformed and placed into the new list (there’s an example of conditioning in a comprehension loop in the section on spiders).

For example, to extract the navigable string from every element of artistlist, we can set item to a, expression to a.string, and list to artistlist:

artists = [a.string for a in artistlist]
artists
['Baby Rose f/ BADBADNOTGOOD',
 'Angie McMahon',
 'Willie Nelson and Daniel Lanois',
 'Lucy Dacus',
 'Brigitte Calls Me Baby',
 'Kashus Culpepper',
 'Deep Sea Diver',
 'The Devil Makes Three',
 'The Barons',
 'Sunflower Bean',
 'Ray LaMontagne',
 'Spoon',
 'Noeline Hofmann',
 'Inhaler',
 'John Prine',
 '49 Winchester',
 'Ruthie Foster',
 'Joy Oladokun',
 'Death Cab for Cutie',
 'Jeremie Albino',
 'Cristina Vane f/ Molly Tuttle',
 'Ziggy Marley & the Melody Makers',
 'Chuck Prophet',
 'The Vices',
 'Jim Lauderdale',
 'Humbird',
 'ALO',
 'Tracy Chapman',
 'The Bamboos',
 'Oracle Sisters',
 'Ruthie Foster',
 'Local The Neighbour',
 'Kasey Chambers',
 'Hiss Golden Messenger',
 'Daughter of Swords',
 'Soccer Mommy',
 'Pug Johnson',
 'JD McPherson',
 'Guster',
 'Jungle',
 'Johnny Delaware',
 'Nickel Creek',
 'Luke Winslow-King',
 'The English Beat',
 'Bebe Stockwell',
 'Wallice',
 'Jesper Lindell',
 'The Smile',
 'Mumford & Sons',
 'Ray Charles',
 'Kat Edmonson',
 'The Heavy Heavy',
 'Waxahatchee',
 'Johnny Blue Skies',
 'Charley Crockett',
 'Morrissey']

Likewise, we extract the navigable strings for the songs, albums, and times:

songs = [a.string for a in songlist]
albums = [a.string for a in albumlist]
times = [a.string for a in timelist]

Finally, to construct a clean data frame, we create a dictionary that combines these lists and passes this dictionary to the pd.DataFrame() function:

mydict = {'time':times,
          'artist':artists,
         'song':songs,
         'album':albums}
wnrn_df = pd.DataFrame(mydict)
wnrn_df
time artist song album
0 10:01 AM Baby Rose f/ BADBADNOTGOOD Weekness Slow Burn EP
1 9:57 AM Angie McMahon Untangling Light Sides EP
2 9:52 AM Willie Nelson and Daniel Lanois The Maker Teatro
3 9:49 AM Lucy Dacus Ankles Forever Is A Feeling
4 9:44 AM Brigitte Calls Me Baby Too Easy The Future Is Our Way Out
5 9:41 AM Kashus Culpepper After Me? (Single)
6 9:37 AM Deep Sea Diver Shovel Billboard Heart
7 9:31 AM The Devil Makes Three Spirits Spirits
8 9:27 AM The Barons Would You Want It (If You Had It) (Single)
9 9:24 AM Sunflower Bean Champagne Taste Mortal Primetime
10 9:18 AM Ray LaMontagne And They Call Her California Long Way Home
11 9:14 AM Spoon The Underdog Ga Ga Ga Ga Ga
12 9:10 AM Noeline Hofmann Lightning in July (Prairie Fire) Purple Gas
13 9:04 AM Inhaler Your House Open Wide
14 8:59 AM John Prine Lake Marie Lost Dogs & Mixed Blessings
15 8:55 AM 49 Winchester Miles to Go (Single)
16 8:51 AM Ruthie Foster Rainbow Mileage
17 8:45 AM Joy Oladokun DUST/DIVINITY Observations From A Crowded Room
18 8:41 AM Death Cab for Cutie Cath Narrow Stairs
19 8:38 AM Jeremie Albino Rolling Down the 405 Our Time In The Sun
20 8:31 AM Cristina Vane f/ Molly Tuttle Hear My Call Hear My Call
21 8:27 AM Ziggy Marley & the Melody Makers Tomorrow People Conscious Party
22 8:19 AM Chuck Prophet First Came The Thunder Wake the Dead
23 8:15 AM The Vices Before It Might Be Gone Before It Might Be Gone
24 8:11 AM Jim Lauderdale Don't Leave Your Light Low Persimmons
25 8:09 AM Humbird Blueberry Bog Right On
26 8:03 AM ALO Blank Canvas Frames
27 8:00 AM Tracy Chapman You're the One Let It Rain
28 7:55 AM The Bamboos Hard Up Hard Up
29 7:52 AM Oracle Sisters Alouette Divinations
30 7:48 AM Ruthie Foster Singing the Blues Promise of a Brand New Day
31 7:43 AM Local The Neighbour Cruise Control VALLEY pt. 2
32 7:39 AM Kasey Chambers Broken Cup Backbone
33 7:35 AM Hiss Golden Messenger Heart like a Levee Heart Like a Levee
34 7:33 AM Daughter of Swords Alone Together Cardinals At The Window
35 7:22 AM Soccer Mommy Circle the Drain Color Theory
36 7:18 AM Pug Johnson Believer El Cabron
37 7:14 AM JD McPherson I Can't Go Anywhere With You Nite Owls
38 7:10 AM Guster Amsterdam Keep It Together
39 7:07 AM Jungle Keep Me Satisfied (Single)
40 7:02 AM Johnny Delaware Running Para Llevar
41 6:58 AM Nickel Creek This Side This Side
42 6:55 AM Luke Winslow-King Flash-A-Magic Flash-A-Magic
43 6:52 AM The English Beat Best Friend I Just Can't Stop It
44 6:49 AM Bebe Stockwell Minor Inconveniences (Single)
45 6:45 AM Wallice I Want You Yesterday The Jester
46 6:42 AM Jesper Lindell One of These Rainy Days Before the Sun
47 6:37 AM The Smile No Words Cutouts
48 6:32 AM Mumford & Sons Rushmere Rushmere
49 6:25 AM Ray Charles What'd I Say Pts I and II What'd I Say
50 6:22 AM Kat Edmonson Keep Movin' Keep Movin'
51 6:17 AM The Heavy Heavy Feel One of a Kind
52 6:13 AM Waxahatchee Can't Do Much Saint Cloud
53 6:09 AM Johnny Blue Skies If The Sun Never Rises Again Passage Du Desir
54 6:04 AM Charley Crockett Lonesome Drifter Lonesome Drifter
55 6:00 AM Morrissey Suedehead Viva Hate

5.5. Building a Spider#

At the bottom of the WNRN playlist on https://spinitron.com/WNRN/ there are links to older song playlists. Let’s extend our example by building a spider to capture the data that exists on these links as well. A spider is a web scraper that follows links on a page automatically and scrapes from those links as well.

I look at the page source for these links, and find that they are contained in a <div class="recent-playlists"> tag. I start by finding this tag. As there’s only one occurrence, I can use .find() instead of .find_all():

recent = wnrn.find("div", "recent-playlists")
recent
<div class="recent-playlists">
<h4>Recent</h4>
<div class="grid-view" id="w2"><div class="summary"></div>
<table class="table table-bordered table-narrow"><tbody>
<tr data-key="0"><td class="show-time">5:00 AM</td><td></td><td><strong><a href="/WNRN/pl/20207753/WNRN-2-11-25-5-00-AM">WNRN 2/11/25, 5:00 AM</a></strong> with <a href="/WNRN/dj/104061/WNRN">WNRN</a></td></tr>
<tr data-key="1"><td class="show-time">4:00 AM</td><td></td><td><strong><a href="/WNRN/pl/20207688/WNRN-2-11-25-4-03-AM">WNRN 2/11/25, 4:03 AM</a></strong> with <a href="/WNRN/dj/104061/WNRN">WNRN</a></td></tr>
<tr data-key="2"><td class="show-time">8:00 PM</td><td></td><td><strong><a href="/WNRN/pl/20206023/WNRN">WNRN</a></strong> (Music)</td></tr>
<tr data-key="3"><td class="show-time">6:00 PM</td><td></td><td><strong><a href="/WNRN/pl/20205530/World-Caf%C3%A9">World Café</a></strong> (Music) with <a href="/WNRN/dj/179987/Raina-Douris-and-Stephen-Kallao">Raina Douris and Stephen Kallao</a></td></tr>
<tr data-key="4"><td class="show-time">6:00 AM</td><td></td><td><strong><a href="/WNRN/pl/20202904/WNRN">WNRN</a></strong> (Music)</td></tr>
</tbody></table>
</div></div>

Notice that all of the addresses we need are contained in <a> tags. We can extract these <a> tags with .find_all():

recent_atags = recent.find_all("a")
recent_atags
[<a href="/WNRN/pl/20207753/WNRN-2-11-25-5-00-AM">WNRN 2/11/25, 5:00 AM</a>,
 <a href="/WNRN/dj/104061/WNRN">WNRN</a>,
 <a href="/WNRN/pl/20207688/WNRN-2-11-25-4-03-AM">WNRN 2/11/25, 4:03 AM</a>,
 <a href="/WNRN/dj/104061/WNRN">WNRN</a>,
 <a href="/WNRN/pl/20206023/WNRN">WNRN</a>,
 <a href="/WNRN/pl/20205530/World-Caf%C3%A9">World Café</a>,
 <a href="/WNRN/dj/179987/Raina-Douris-and-Stephen-Kallao">Raina Douris and Stephen Kallao</a>,
 <a href="/WNRN/pl/20202904/WNRN">WNRN</a>]

The resulting list contains the web endpoints we need, and also some web endpoints we don’t need: we want the URLs that contain the string /pl/ as these are playlists, and we want to exclude the URLs that contain the string /dj/ as these pages refer to a particular DJ. We need a comprehension loop that loops across these elements, extracts the href attribute of the entries that include /pl/, and ignore the entries that include /dj/. We again use this syntax:

newlist = [ expression for item in oldlist if condition ]

In this case:

  • newlist is a list containing the URLs we want to direct our spider to. I call it urls.

  • item is one element of recent_atags, which I will call pl.

  • expression is code that extracts the web address from the href attribute of the <a> tag, so here the code would be pl['href'].

  • Finally, condition is a logical statement that should be True if the web address contains /pl/ and False if the web address contains /dj/. Here, the conditional statement should be if "/pl/" in pl['href']. This code will look for the string "/pl/" inside the string called by pl['href'] and return True or False depending on whether this string is found.

Putting all this syntax together gives us our list of playlist URLs:

wnrn_url = [pl['href'] for pl in recent_atags if "/pl/" in pl['href']]
wnrn_url
['/WNRN/pl/20207753/WNRN-2-11-25-5-00-AM',
 '/WNRN/pl/20207688/WNRN-2-11-25-4-03-AM',
 '/WNRN/pl/20206023/WNRN',
 '/WNRN/pl/20205530/World-Caf%C3%A9',
 '/WNRN/pl/20202904/WNRN']

First, we need to collect all of the code we created above to extract the artist, song, album, and play times from the HTML code. We define a function that does all of this work. We specify one argument for this function, the URL, so that all the function needs is the URL and it can output a clean dataframe. I name the function wnrn_spider():

def wnrn_spider(url):
    """Perform web scraping for any WNRN playlist given the available link"""
    
    headers = {'user-agent': 'Kropko class example (jkropko@virginia.edu)'}
    r = requests.get(url, headers=headers)
    wnrn = BeautifulSoup(r.text, 'html')
    
    artistlist = wnrn.find_all("span", "artist")
    songlist = wnrn.find_all("span", "song")
    albumlist = wnrn.find_all("span", "release")
    timelist = wnrn.find_all("td", "spin-time")
    
    artists = [a.string for a in artistlist]
    songs = [a.string for a in songlist]
    albums = [a.string for a in albumlist]
    times = [a.string for a in timelist]
    
    mydict = {'time':times, 'artist':artists, 'song':songs, 'album':albums}
    wnrn_df = pd.DataFrame(mydict)
    
    return wnrn_df

We can pass any of the URLs we collected to our function and get the other playlists. We will have to add the domain “https://spinitron.com” to the beginning of each of the URLs we collected:

wnrn2 = wnrn_spider('https://spinitron.com/' + wnrn_url[0])
wnrn2
time artist song album
0 5:00 AM The Avett Brothers February Seven The Carpenter
1 5:04 AM Michael Kiwanuka The Rest Of Me Small Changes
2 5:07 AM Randall Bramblett Throw My Cane Away Paradise Breakdown
3 5:10 AM Michael Franti & Spearhead Say Hey All Rebel Rockers
4 5:15 AM Becca Mancari Hunter The Greatest Part
5 5:17 AM The Lumineers Same Old Song Automatic
6 5:20 AM Circa Waves Like You Did Before Death & Love Pt. 1
7 5:23 AM The Mavericks Things I Cannot Change Super Colossal Smash Hits of the 9
8 5:27 AM Clairo Amoeba Sling
9 5:31 AM Olivia Wolf Cosmic Appalachian Radio Silver Rounds
10 5:33 AM flipturn Rodeo Clown Burnout Days
11 5:42 AM Moby Porcelain Play
12 5:46 AM Sofia Valdes Already Yours Sofia Valdes
13 5:50 AM Kris Delmhorst I Won't Be Long Ghosts In the Garden
14 5:53 AM Julien Baker & TORRES Sugar In The Tank Send A Prayer My Way
15 5:56 AM The Shins New Slang Oh, Inverted World!

Our goal here is to loop across all the URLs we collected, extract the data in a clean data frame, and append these data frames together to construct a longer playlist. To do that, we will use a for loop, which has the following syntax:

for index in list:
    expressions

This syntax is similar to the syntax we used to build a comprehension loop. list is an existing list, and index stands in for one element of this list. For each element of the list, we execute the code contained in expressions, which can use the index.

For our spider, we will use the following steps:

  1. We take the data we already scraped from https://spinitron.com/WNRN (saved as wnrn_df) and clone it as a new variable named wnrn_total_playlist. It is important that we make a copy, and that we do not overwrite wnrn_df. We will be repeatedly saving over wnrn_total_playlist within the loop, and if we do not overwrite wnrn_df, it gives us a stable data frame to return to as a starting point if we need to rerun this loop.

  2. We use a for loop to loop across all the web addresses inside wnrn_url.

  3. In the for loop, we use the wnrn_spider() function to extract the playlist data from each of the URLs inside wnrn_url.

  4. In the for loop, we use the pd.concat() method to attach the new data to the bottom of the existing data, matching corresponding columns.

The code is as follows:

wnrn_total_playlist = wnrn_df 
for w in wnrn_url:
    moredata = wnrn_spider('https://spinitron.com/' + w) 
    wnrn_total_playlist = pd.concat([wnrn_total_playlist, moredata], ignore_index=True) 

We now have a data frame that combines all of the playlists on https://spinitron.com/WNRN and on the playlists linked to under “Recent”:

wnrn_total_playlist
time artist song album
0 10:01 AM Baby Rose f/ BADBADNOTGOOD Weekness Slow Burn EP
1 9:57 AM Angie McMahon Untangling Light Sides EP
2 9:52 AM Willie Nelson and Daniel Lanois The Maker Teatro
3 9:49 AM Lucy Dacus Ankles Forever Is A Feeling
4 9:44 AM Brigitte Calls Me Baby Too Easy The Future Is Our Way Out
... ... ... ... ...
383 5:38 PM Electric Guest This Head I Hold Mondo
384 5:41 PM Ray LaMontagne And They Call Her California Long Way Home
385 5:47 PM 49 Winchester Miles to Go (Single)
386 5:51 PM Hurray for the Riff Raff Living in the City The Navigator
387 5:55 PM The B-52s Rock Lobster The B-52s

388 rows × 4 columns