Intro to Python and Web Scraping

(Download Files for this Tutorial Here)


I. Anaconda Crash Course: Using Anaconda (“Conda”) to Supplement Python

Python is a valuable scripting language for data analysis and management; however managing a Python project environment can be nuanced and tricky. Anaconda is a platform built to complement Python by creating customizable and easily accessible environments in which you can run Python scripts.

For reference, the Anaconda homepage is found at the following address.

https://www.continuum.io/why-anaconda

The following tutorial runs through the installation of Anaconda, and then introduces you to the concepts behind Anaconda that make it a nice and useful Python development environment.


Install Anaconda (aka Conda)

The Anaconda homepage contains the materials that you need to install Anaconda on your machine. You will primarily be using Anaconda through the command line, so you will have to get comfortable working on the command line.

II. Check Anaconda Version and Install

The first step is to open Terminal and check to see if you have Anaconda installed. If not, we will install it. To check the version, follow the following commands.

A. Open Terminal

B. Check Version

The syntax to access Anaconda on the command line is simply ‘conda’. To check the version you have installed, use the following:

conda info

If you have it installed, you will see platform information, version details, and environment paths after you hit enter, if not, the terminal will not recognize the command.

C. Install Anaconda

To install ‘Conda’, navigate to the Anaconda downloads page at:

Anaconda Homepage and Downloads

Here, pick your system (Mac/Windows) and the Python version. In our case, we are going to pick Mac and select version 3.6. Use the graphical installer, it will provide us a wizard that will step us through the installation process. Download the installer, double click the package file and follow the instructions. Just a heads up, the installation process takes 5-10 minutes, its a big program, but is straight forward.

If you run into problems installing, or you get an error that states that Anaconda cannot be install in the default location, visit this page for short instructions on how to troubleshoot installation.

Anaconda Installation Docs

Anaconda is contained in one directory, so if you ever need to uninstall Anaconda, use Terminal to remove the entire Anaconda directory using rm -rf ~/anaconda.

We used Python 3, not Python 2. The guidelines on the site describe that we should use whichever version we intend to use most often, but ultimately it will not matter that much. Anaconda supports both, and if you ever want to use Python 2, you can create an environment that uses Python 2 and activate it. The main reason you would want to use Python 2 is that Linux distributions and Macs, Python 2.7 is still the default, and because the Python ecosystem has amassed a significant amount of quality software over the years in which some of it does not yet work on 3. Python 3, however, is designed to be more robust and fixes a lot of bugs in Python 2, so in the future, expect to see a continued migration to Python 3. We are set up with Python 3 as our default, but since we are using Anaconda, if we want to set up a Python 2 instance at some point, it will be easy to do!

III. Confirm the installation worked properly

Once we are finished with the installation, check to make sure it installed correctly by performing a version check.

conda info

If you see a 4.X.X version number popup, and with platform and environment information, the installation worked. Now we can begin working with Conda.


Additional Reading and Resources

Anaconda 30-minute Test Drive

http://conda.pydata.org/docs/test-drive.html

Conda Command Line Cheatsheet -

http://conda.pydata.org/docs/_downloads/conda-cheatsheet.pdf

Mac Command Line Cheatsheet –

https://github.com/0nn0/terminal-mac-cheatsheet/wiki/Terminal-Cheatsheet-for-Mac-(-basics-)

Python Documentation -

https://docs.python.org/3/library/index.html


1. Working with Python

Python is an increasingly popular high-level programming language. It emphasizes legibility over highly complex structure. Python innately provides simple data structures allowing for easy data manipulation. Python provides a simple approach to object-oriented programming, which in turn allows for intuitive programming, and has resulted in a large user community that has created numerous libraries that extend the basic capacities of the language.

Python is an "interpretted" language. This means that every Python command that is executed is actually translated to lower-level programming languages. Lower-level programming languages are very fast and powerful, but writing programs in these languages can be difficult.

There are two main versions of Python, these are Python 2 and Python 3. Python 3 is newer, and remove bugs and idiosyncracies of Python 2, however Python 2 is still heavily used. While the fundamentals of the two versions are the same, there are some differences (mostly syntactical) between the two and unfortunately Python 3 is NOT backwards compatible, so always double check which version of Python is being used when you work with it. In this class, we are using Python 3.

There are a number of great Python tutorials available on the web, some can be found here: </p>

There are also some excellent Python textbooks and cookbooks. A simple Amazon search will reveal many. In particular, we recommend and are using the following from the MIT Press: </p>

2. Jupyter Notebooks:

IPython

A Jupyter Notebook (formerly called iPython) is a tool for interactively writing and executing Python code. It allows the programmer to easily write and test code by allowing snippets of code and their results to be displayed side-by-side. Each snippet of code is called a "cell". It promotes the ease of documentation by allowing some cells to contain text, html code, images, or even Latex. Jupyter is particularly useful for Big Data computation, as it allows for parallel processing.

Let's switch over to a Jupyter Notebook for the rest of this tutorial. First, create an environment that is running Python 3 in terminal. We can name this anything, but name it python3 so we can remember easily what it is.

conda create --name python3 python=3.6

Now we want to work in this environment. Activate python3 using the following.

source activate python3

Then, navigate to the folder containing the tutorial files you've downloaded.

cd [folder name]/[sub-folder name]/[etc]

Finally launch a Jupyter notebook, and open the "Intro to Python and Web Scraping.ipynb" file

jupyter notebook

3. Python Libraries

Python is a dynamically typed language. A language has dynamic typing when variable types are not predefined like in a compiled language; the type of a value is evaluated when the code is run, based on how you are attempting to use it.

Dynamic typing and a number of other language specific characteristics, like readability and reusability, make it a very popular programming language with a large user community. However, Python on itself only provides a basic number of modules and functionality. In order to extend Python’s functionality, the active community has created a very large number of libraries. A library is a built-in or external module that can be imported into our current code to add functionality. Libraries usually take advantage of Object-Oriented-Programming, defining Python objects in additional scripts that can then be instantiated in our current code.

Loading libraries into our current context can be expensive; for that reason, Python requires us to explicitly load the libraries that we want to use:

import math

We can be more specific and import only specific classes or functions of the library:

from math import pi

We can also change the name of the library when it gets imported:

import matplotlib as plt

4. Web Scraping using Beautiful Soup

Let's scrape some data using a fun library called Beautiful Soup. We'll create a CSV dataset of the a table on 311 reported Rodent Incidents around Boston.

The website we are going to scrape is here.

County Housing Statistics

Let's get started!

Importing Modules

First import modules. import requests imports the requests module, and import bs4 imports the Beautiful Soup library.

In [2]:
import requests
import bs4

# If you don't have Beautiful Soup, install with 'conda install beautifulsoup' in terminal

Testing out Requests

Requests will allow us to load a webpage into python so that we can parse it and manipulate it. Test this by running the following. Enter the following commands in terminal, and hit enter after entering each to run each of them.

In [3]:
response = requests.get('http://duspviz.mit.edu/_assets/data/county_housing_stats.html')
print(response.text) # Print the output

This allowed us to access all of the content from the source code of the webpage with Python, which we can now parse and extract data. It even printed to our console. Pretty cool!

Testing out Beautiful Soup

Our next big step is to test out Beautiful Soup. Let's talk about what this is...

What is Beautiful Soup?

Beautiful Soup is a Python library for parsing data out of HTML and XML files (aka webpages). It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. The major concept with Beautiful Soup is that it allows you to access elements of your page by following the CSS structures, such as grabbing all links, all headers, specific classes, or more. It is a powerful library. Once we grab elements, Python makes it easy to write the elements or relevant components of the elements into other files, such as a CSV, that can be stored in a database or opened in other software.

The sample webpage we are using contains data on 'rodent incidents' in the greater Boston area. Let's use this file to explore the tree, and extract some data.

iv. Make the Soup

First, we have to turn the website code into a Python object. We have already imported the Beautiful Soup library, so we can start calling some of the methods in the libary. Replace print response.text with the following. This turns the text into an Python object named soup.

An important note: You need to specify the specific parser that Beautiful Soup uses to parse your text. This is done in the second argument of the BeautifulSoup function. The default is the built in Python parser, which we can call using html.parser

You an also use lxml or html5lib. This is nicely described in the documentation. For our purposes, using the default is fine.

Using the Beautiful Soup prettify() function, we can print the page to see the code printed in a readable and legible manner.

In [4]:
soup = bs4.BeautifulSoup(response.text, "html.parser")
print(soup.prettify()) # Print the output using the 'prettify' function

At any point, if you need a reference, visit the Beautiful Soup documentation for the official descriptions of functions. Prettify is a handy one to see our document in a clean fashion.

With our data from the webpage nicely laid out, Beautiful Soup allows us to now navigate the data structure. We called our Beautiful Soup object soup, so we can run the Beautiful Soup functions on this object. Let's explore some ways to do this, try entering some of the following into your terminal.

In [15]:
# Access the title element
soup.title
Out[15]:
<title>US County Housing Stats</title>
In [16]:
# Access the content of the title element
soup.title.string
Out[16]:
u'US County Housing Stats'
In [17]:
# Access data in the first 'p' tag
soup.p
Out[17]:
<p class="title"><b>U.S. Basic Housing Stats by County</b></p>
In [18]:
# Access data in the first 'a' tag
soup.a
Out[18]:
<a class="link" href="http://example.com/link1" id="link1">Link 1</a>
In [19]:
# Retrieve all links in the document (note it returns an array)
soup.find_all('a')
Out[19]:
[<a class="link" href="http://example.com/link1" id="link1">Link 1</a>,
 <a class="link" href="http://example.com/link2" id="link2">Link 2</a>,
 <a class="link" href="http://example.com/link3" id="link3">Link 3</a>,
 <a class="link" href="http://example.com/link4" id="link4">Link 4</a>]
In [20]:
# Retrieve elements by class equal to link using the attributes argument
soup.findAll(attrs={'class' : 'link'})
Out[20]:
[<a class="link" href="http://example.com/link1" id="link1">Link 1</a>,
 <a class="link" href="http://example.com/link2" id="link2">Link 2</a>,
 <a class="link" href="http://example.com/link3" id="link3">Link 3</a>,
 <a class="link" href="http://example.com/link4" id="link4">Link 4</a>]
In [21]:
# Retrieve a specific link by ID
soup.find(id="link3")
Out[21]:
<a class="link" href="http://example.com/link3" id="link3">Link 3</a>
In [5]:
# Access Data in the table (note it returns an array)
soup.find_all('td')

Working with Arrays

The easiest way to access elements and then either write them to file or manipulate them is to save them as objects themselves. Note that our data is organzed into counties and several numbers. Let's save these to arrays, which are the easiest way to work with the data.

The following gives us an array, we can work with the elements.

In [34]:
data = soup.findAll(attrs={'class':'name'})
print(data[0].string)
print(data[1].string)
print(data[2].string)
print(data[3].string)
Autauga County, Alabama
Baldwin County, Alabama
Barbour County, Alabama
Bibb County, Alabama

You never want to repeat code like this, so turn this into a loop:

In [8]:
data = soup.findAll(attrs={'class':'name'})
for i in data:
    print(i.string)

This array only gives us counties though, let's get all of the data elements from all classes.

In [9]:
data = soup.findAll(attrs={'class':['name','fips','tot-pop','median-income','no-housing-units','med-home-val','owner-occupied','house-w-debt','house-wo-debt']})
for i in data:
    print(i.string)

We have all of our data that was nested in these tags saved to a Python array. Access the elements of the array by using data[x], where x is location in the array. In Python, arrays start at 0, so place 1 in a Python array is actually called by using a 0, and place 8 would be called by a 7.

In [51]:
print(data[0])
print(data[1])
<td class="name">Autauga County, Alabama</td>
<td class="fips">01001</td>

Right now, we get the whole element with those commands. To get just the content, use the following.

In [37]:
print(data[0].string)
print(data[1].string)
Autauga County, Alabama
Baldwin County, Alabama

In the next part, we'll create a script file and run it!

Create and execute Script File (.py)

Open up starter_script.py in Sublime Text and we are going to copy the code below into that file. .py signifies that the file is a python program. Using this method, you can make independently standing python files that can be run. It is located in the scripts folder for the week. Starter script contains all the code below, and is a sample you can use for scraping pages.

For the first lines in the file, lets import modules. import requests imports the requests module, and import bs4 imports the Beautiful Soup library, then, based on what we did above, load the page, turn it into a parseable 'soup', then find the proper elements. Let's put a print at the end so we can see our work as it runs.

In [10]:
import requests
import bs4

# load and get the website
response = requests.get('http://duspviz.mit.edu/_assets/data/county_housing_stats.html')

# create the soup
soup = bs4.BeautifulSoup(response.text, "html.parser")

# find all the tags with class city or number
data = soup.findAll(attrs={'class':['name','fips','tot-pop','median-income','no-housing-units','med-home-val','owner-occupied','house-w-debt','house-wo-debt']})

# print 'data' to console
print(data)

Run this by typing python starter_script.py in terminal. This will execute our program.

You should see an array with our data elements nested within tags. This is what we want!

Write data to a file using a simple loop

Python makes opening a file and writing to it very easy. Let's take this simple dataset and write it to a file that saves in our current working directory. An important note, whatever the working directory is when you start Python will be the root for where your files are read from and written to.

Python also has nice iteration features that allow us to iterate through arrays, lists, and other files. In this following example, manually create a comma-separated document with our data using file writing operations and a while loop.

In pseudo-code:

  1. Open up a file to write in and append data.

  2. Set up parameters for the while loop

  3. Write headers

  4. Run while loop that will write elements of the array to file

  5. When complete, close the file

Once done, open the file on your machine and see your data. Enter the following code into the starter_scirpt.py file below our other code, note what each line is doing.

In [13]:
f = open('county_data.csv','a') # open new file, make sure path to your data file is correct

p = 0 # initial place in array
l = len(data)-1 # length of array minus one


f.write("County, State, FIPS Code, Total Pop, Median Income ($), No. of Housing Units, Median Home Value ($), No. of Owner Occupied Housing Units, No. of Owner Occ. Housing Units with Debt, No. of Owner Occ. Housing Units without Debt\n") #write headers


while p < l: # while place is less than length
    f.write(data[p].string + ", ") # write county and add comma
    p = p + 1 # increment
    f.write(data[p].string + ", ") # write FIPS and add comma
    p = p + 1 # increment
    f.write(data[p].string + ", ") # write Total Pop and add comma
    p = p + 1 # increment
    f.write(data[p].string + ", ") # write Median Income and add comma
    p = p + 1 # increment
    f.write(data[p].string + ", ") # write No. of Housing Units and add comma
    p = p + 1 # increment
    f.write(data[p].string + ", ") # write Median Home Value and add comma
    p = p + 1 # increment
    f.write(data[p].string + ", ") # write No. of Owner Occupied Housing Units and add comma
    p = p + 1 # increment
    f.write(data[p].string + ", ") # write No. of Owner Occ. Housing Units with Debt and add comma
    p = p + 1 # increment
    f.write(data[p].string + "\n") # write No. of Owner Occ. Housing Units without Debt and line break
    p = p + 1 # increment

    
f.close() # close file

Save and run the file. You'll see county_data.txt appear where you designate.

Open county_data.txt in Sublime Text. It's a CSV with the data from the page!

County, State, FIPS Code, Total Pop, Median Income ($), No. of Housing Units...
Autauga County, Alabama, 1001, 55221, 51281, 22582...
Baldwin County, Alabama, 1003, 195121, 50254, 106422...
Barbour County, Alabama, 1005, 26932, 32964, 11810...

Further reading on File Reading and Writing and Iteration in Python can be found at the following links.

Python File Reading and Writing Documentation

We created this CSV manually to illustrate some basic Python. Python has modules and features that support CSV as well that are very useful and handy. These are best if you are reading in a CSV, allowing you to access the elements of the CSV. You can read more about the built in CSV module here.


Credits

Prepared by Mike Foster & Luke Mich


Return to DUSPviz tutorials page