{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Web Scraping Worksheet\n", "\n", "These problem sets focus on using the Beautiful Soup library to scrape web pages.\n", "\n", "## Problem Set #1: Basic scraping\n", "\n", "I've made a web page for you to scrape. It's available [here](http://static.decontextualize.com/widgets2016.html). The page concerns the catalog of a famous [widget](http://en.wikipedia.org/wiki/Widget) company. You'll be answering several questions about this web page. In the cell below, I've written some code so that you end up with a variable called `html_str` that contains the HTML source code of the page, and a variable `document` that stores a Beautiful Soup object." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from bs4 import BeautifulSoup\n", "import requests\n", "html_str = requests.get(\"http://static.decontextualize.com/widgets2016.html\").text\n", "document = BeautifulSoup(html_str, \"html.parser\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, in the cell below, use Beautiful Soup to write an expression that evaluates to the number of `

` tags contained in `widgets2016.html`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, in the cell below, write an expression or series of statements that displays the telephone number beneath the \"Widget Catalog\" header." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the cell below, use Beautiful Soup to write some code that prints the names of all the widgets on the page. After your code has executed, `widget_names` should evaluate to a list that looks like this (though not necessarily in this order):\n", "\n", "```\n", "Skinner Widget\n", "Widget For Furtiveness\n", "Widget For Strawman\n", "Jittery Widget\n", "Silver Widget\n", "Divided Widget\n", "Manicurist Widget\n", "Infinite Widget\n", "Yellow-Tipped Widget\n", "Unshakable Widget\n", "Self-Knowledge Widget\n", "Widget For Cinema\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem set #2: Widget dictionaries\n", "\n", "For this problem set, we'll continue to use the HTML page from the previous problem set. In the cell below, I've made an empty list and assigned it to a variable called `widgets`. Write code that populates this list with dictionaries, one dictionary per widget in the source file. The keys of each dictionary should be `partno`, `wname`, `price`, and `quantity`, and the value for each of the keys should be the value for the corresponding column for each row. After executing the cell, your list should look something like this:\n", "\n", "```\n", "[{'partno': 'C1-9476',\n", " 'price': '$2.70',\n", " 'quantity': u'512',\n", " 'wname': 'Skinner Widget'},\n", " {'partno': 'JDJ-32/V',\n", " 'price': '$9.36',\n", " 'quantity': '967',\n", " 'wname': u'Widget For Furtiveness'},\n", " ...several items omitted...\n", " {'partno': '5B-941/F',\n", " 'price': '$13.26',\n", " 'quantity': '919',\n", " 'wname': 'Widget For Cinema'}]\n", "```\n", "\n", "And this expression:\n", "\n", " widgets[5]['partno']\n", " \n", "... should evaluate to:\n", "\n", " LH-74/O\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets = []\n", "\n", "# your code here\n", "\n", "# end your code\n", "\n", "widgets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the cell below, duplicate your code from the previous question. Modify the code to ensure that the values for `price` and `quantity` in each dictionary are floating-point numbers and integers, respectively. I.e., after executing the cell, your code should display something like this:\n", "\n", " [{'partno': 'C1-9476',\n", " 'price': 2.7,\n", " 'quantity': 512,\n", " 'widgetname': 'Skinner Widget'},\n", " {'partno': 'JDJ-32/V',\n", " 'price': 9.36,\n", " 'quantity': 967,\n", " 'widgetname': 'Widget For Furtiveness'},\n", " ... some items omitted ...\n", " {'partno': '5B-941/F',\n", " 'price': 13.26,\n", " 'quantity': 919,\n", " 'widgetname': 'Widget For Cinema'}]\n", "\n", "(Hint: Use the `float()` and `int()` functions. You may need to use string slices to convert the `price` field to a floating-point number.)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets = []\n", "\n", "# your code here\n", "\n", "# end your code\n", "\n", "widgets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Great! I hope you're having fun. In the cell below, write an expression or series of statements that uses the `widgets` list created in the cell above to calculate the total number of widgets that the factory has in its warehouse.\n", "\n", "Expected output: `7928`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the cell below, write some Python code that prints the names of widgets whose price is above $9.30.\n", "\n", "Expected output:\n", "\n", "```\n", "Widget For Furtiveness\n", "Jittery Widget\n", "Silver Widget\n", "Infinite Widget\n", "Widget For Cinema\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem set #3: Sibling rivalries\n", "\n", "In the following problem set, you will yet again be working with the data in `widgets2016.html`. In order to accomplish the tasks in this problem set, you'll need to learn about Beautiful Soup's `.find_next_sibling()` method. Here's some information about that method, cribbed from the notes:\n", "\n", "Often, the tags we're looking for don't have a distinguishing characteristic, like a class attribute, that allows us to find them using `.find()` and `.find_all()`, and the tags also aren't in a parent-child relationship. This can be tricky! For example, take the following HTML snippet, (which I've assigned to a string called `example_html`):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "example_html = \"\"\"\n", "

Camembert

\n", "

A soft cheese made in the Camembert region of France.

\n", "\n", "

Cheddar

\n", "

A yellow cheese made in the Cheddar region of... France, probably, idk whatevs.

\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If our task was to create a dictionary that maps the name of the cheese to the description that follows in the `

` tag directly afterward, we'd be out of luck. Fortunately, Beautiful Soup has a `.find_next_sibling()` method, which allows us to search for the next tag that is a sibling of the tag you're calling it on (i.e., the two tags share a parent), that also matches particular criteria. So, for example, to accomplish the task outlined above:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "example_doc = BeautifulSoup(example_html, \"html.parser\")\n", "cheese_dict = {}\n", "for h2_tag in example_doc.find_all('h2'):\n", " cheese_name = h2_tag.string\n", " cheese_desc_tag = h2_tag.find_next_sibling('p')\n", " cheese_dict[cheese_name] = cheese_desc_tag.string\n", "\n", "cheese_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With that knowledge in mind, let's go back to our widgets. In the cell below, write code that uses Beautiful Soup, and in particular the `.find_next_sibling()` method, to print the part numbers of the widgets that are in the table *just beneath* the header \"Hallowed Widgets.\"\n", "\n", "Expected output:\n", "\n", "```\n", "MZ-556/B\n", "QV-730\n", "T1-9731\n", "5B-941/F\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Okay, now, the final task. If you can accomplish this, you are truly an expert web scraper. I'll have little web scraper certificates made up and I'll give you one, if you manage to do this thing. And I know you can do it!\n", "\n", "In the cell below, I've created a variable `category_counts` and assigned to it an empty dictionary. Write code to populate this dictionary so that its keys are \"categories\" of widgets (e.g., the contents of the `

` tags on the page: \"Forensic Widgets\", \"Mood widgets\", \"Hallowed Widgets\") and the value for each key is the number of widgets that occur in that category. I.e., after your code has been executed, the dictionary `category_counts` should look like this:\n", "\n", "```\n", "{'Forensic Widgets': 3,\n", " 'Hallowed widgets': 4,\n", " 'Mood widgets': 2,\n", " 'Wondrous widgets': 3}\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "category_counts = {}\n", "# your code here\n", "\n", "# end your code\n", "category_counts" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Congratulations! You're done." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" } }, "nbformat": 4, "nbformat_minor": 1 }