{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c001",
   "metadata": {},
   "source": [
    "# Reading web pages with requests and Beautiful Soup: arXiv hardware papers"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c002",
   "metadata": {},
   "source": [
    "**Three lessons, one notebook.** This notebook follows three lessons of the course, one after the other: part 1, [From a Web Page to Data: Beautiful Soup](https://dvirross.com/courses/intro-data-science/data-collection-beautifulsoup) (tasks 1 to 3); part 2, [From One Element to All Entries: find_all, Numbers and Missing Values](https://dvirross.com/courses/intro-data-science/data-collection-find-all) (tasks 4 to 6); part 3, [From a List to Many Pages: Following Links](https://dvirross.com/courses/intro-data-science/data-collection-linked-pages) (tasks 7 to 9). A heading marks the place where each part starts. The tasks are numbered from 1 to 9 without a break, so `check(N)` always belongs to the task N of the part that holds it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c003",
   "metadata": {},
   "source": [
    "# Part 1: From a Web Page to Data: Beautiful Soup\n",
    "\n",
    "The lesson page of this part: [From a Web Page to Data: Beautiful Soup](https://dvirross.com/courses/intro-data-science/data-collection-beautifulsoup)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c004",
   "metadata": {},
   "source": [
    "In this lesson we learn how a program asks for a web page, how the tags of an [HTML](https://dvirross.com/courses/intro-data-science/glossary#html) page are organized into elements with attributes, and how the Python library Beautiful Soup finds one element and reads its text and its attributes.\n",
    "\n",
    "## Which hardware papers appeared this month?\n",
    "\n",
    "[arXiv](https://arxiv.org) (pronounced \"archive\") is a free archive where researchers post scientific papers. Its section Hardware Architecture, `cs.AR`, lists papers on how processors, memories and accelerators are designed. The list of October 2026 is one web page with 266 entries. We want the title, the link and the number of authors of each paper. The list is shown as a web page, and a person can read the data there.\n",
    "\n",
    "<figure class=\"lesson-shot\">\n",
    "<a href=\"/images/course-illustrations/data-collection/arxiv-listing-entries.webp\"><img src=\"/images/course-illustrations/data-collection/arxiv-listing-entries.webp\" width=\"960\" height=\"400\" alt=\"The beginning of the arXiv list of Hardware Architecture papers for October 2026: the line with the total number of entries, and the first entries, each with its title, its authors and links to the paper. Four numbered markers point to the total, a title, the authors and the links.\" loading=\"lazy\"></a>\n",
    "<figcaption>The list of October 2026, as the browser shows it. Marker 1: the number of entries in the month. Marker 2: the title of a paper. Marker 3: its authors. Marker 4: the links to its pdf, its html version and other formats.</figcaption>\n",
    "</figure>\n",
    "\n",
    "Reading data from web pages with a program is called **[web scraping](https://dvirross.com/courses/intro-data-science/glossary#web-scraping)**. A program can do what the person does if it can read the page. Counting the authors of 266 papers by eye takes an hour; a program takes a second, and it does the same for the list of the next month. In this lesson a program gets the page and reads the title and the link of the first paper from it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c005",
   "metadata": {},
   "source": [
    "## Setup: the libraries and the check function\n",
    "\n",
    "No account and no key are needed. The next cell imports `requests` and `beautifulsoup4` (Colab has both; the cell installs them if the session does not). The pages that the code reads are saved copies of arXiv pages, kept on the public site of the course, so the numbers are the same for everyone. The cells marked **Live site** read arXiv itself, so their numbers can differ from the page, and they can fail when the site does not answer. They are switched off (`RUN_LIVE = False`), so that a whole class does not send requests to arXiv from one address at once."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c006",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:21.879906Z",
     "iopub.status.busy": "2026-11-22T13:17:21.879718Z",
     "iopub.status.idle": "2026-11-22T13:17:21.995552Z",
     "shell.execute_reply": "2026-11-22T13:17:21.993945Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "requests 2.34.2 | beautifulsoup4 4.15.0\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    import bs4, requests\n",
    "except ImportError:\n",
    "    !pip install -q requests beautifulsoup4\n",
    "    import bs4, requests\n",
    "print('requests', requests.__version__, '| beautifulsoup4', bs4.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c007",
   "metadata": {},
   "source": [
    "The next cell defines the function `check(task_number)`. After you run the cell of a task, run the cell under it: `check` runs your cell again, collects what it prints, and compares it with the expected output. It tells you whether the output is right, and where it differs if not; it never shows the solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c008",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:21.998048Z",
     "iopub.status.busy": "2026-11-22T13:17:21.997774Z",
     "iopub.status.idle": "2026-11-22T13:17:22.010734Z",
     "shell.execute_reply": "2026-11-22T13:17:22.009358Z"
    }
   },
   "outputs": [],
   "source": [
    "import ast, contextlib, hashlib, io\n",
    "\n",
    "# The expected output of each task, as hashes of its lines (the solutions are not stored here).\n",
    "EXPECTED = {int(k): v for k, v in {\n",
    "    '1': [\n",
    "        'a4ca3edcead4'\n",
    "    ],\n",
    "    '2': [\n",
    "        '2dfe249ea3aa'\n",
    "    ],\n",
    "    '3': [\n",
    "        'c9ad4f15cacd'\n",
    "    ],\n",
    "    '4': [\n",
    "        'cacbc3d3f1c4'\n",
    "    ],\n",
    "    '5': [\n",
    "        '19581e27de7c'\n",
    "    ],\n",
    "    '6': [\n",
    "        '7b1bd53949b7'\n",
    "    ],\n",
    "    '7': [\n",
    "        '4e07408562be'\n",
    "    ],\n",
    "    '8': [\n",
    "        'ead42beead86'\n",
    "    ],\n",
    "    '9': [\n",
    "        '4652614c4d87'\n",
    "    ]\n",
    "}.items()}\n",
    "\n",
    "\n",
    "def check(task):\n",
    "    \"\"\"Run the last cell that ran (not a check) again and compare what it prints with the expected output of the task.\"\"\"\n",
    "    if task not in EXPECTED:\n",
    "        print('There is no such task: ', task)\n",
    "        return\n",
    "    cells = [s for s in In[:-1] if s.strip() and not s.lstrip().startswith('check(')]   # In: the cells that ran, kept by IPython\n",
    "    tree = ast.parse(cells[-1] if cells else '')\n",
    "    last = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None   # a bare last expression counts as printed\n",
    "    out = io.StringIO()\n",
    "    try:\n",
    "        with contextlib.redirect_stdout(out):\n",
    "            exec(compile(tree, '<task>', 'exec'), globals())\n",
    "            if last is not None:\n",
    "                value = eval(compile(ast.Expression(last.value), '<task>', 'eval'), globals())\n",
    "                if value is not None:\n",
    "                    print(repr(value))\n",
    "    except Exception as error:\n",
    "        print('The cell raised an error:', type(error).__name__ + ':', error)\n",
    "        return\n",
    "    got = [hashlib.sha256(line.rstrip().encode()).hexdigest()[:12] for line in out.getvalue().rstrip().splitlines()]\n",
    "    want = EXPECTED[task]\n",
    "    if not got:\n",
    "        print('Nothing was printed. Print the answer in the task cell, run it, and run `check` straight after it.')\n",
    "    elif len(got) != len(want):\n",
    "        print('The cell printed {got} line(s) and the task expects {want}. Re-read the task and the hint.'.format(got=len(got), want=len(want)))\n",
    "    elif got != want:\n",
    "        print('Line {k} is different from the expected output. Re-read the task and the hint.'.format(k=next(i for i in range(len(want)) if got[i] != want[i]) + 1))\n",
    "    else:\n",
    "        print('OK: the output is as expected.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c009",
   "metadata": {},
   "source": [
    "## The practice site and its saved copy\n",
    "\n",
    "The pages of this unit are real pages of arXiv, and its **[`robots.txt`](https://dvirross.com/courses/intro-data-science/glossary#robots-txt)** (a file in which a site tells programs which of its pages they may read) allows the pages we use. The browser lets a page on this site talk only to this site, so the code on this page reads a **saved copy** of the pages, kept on this site: the list of October 2026 (its first 25 entries) and the page of each of its first eight papers. The copies are the pages as arXiv sent them on 13 November 2026, unchanged. The notebooks of this unit run the same code on the copy; their cells for the live site, where the numbers can differ, are off (`RUN_LIVE = False`): a class shares one address, and arXiv asks for 15 seconds between requests. The saved pages hold descriptive metadata of the papers (titles, authors, abstracts and subjects), which arXiv makes available for free use under the CC0 1.0 public-domain dedication, according to the [terms of use of its API](https://info.arxiv.org/help/api/tou.html); the papers themselves belong to their authors and are not copied here. The source of every page is [arXiv.org](https://arxiv.org). The links inside a copy lead to arXiv itself, so they do not open from this site.\n",
    "\n",
    "## Four rules before reading a site\n",
    "\n",
    "A program that reads a site is a guest. Four rules keep it a welcome one:\n",
    "\n",
    "- We read the [`robots.txt`](https://dvirross.com/courses/intro-data-science/glossary#robots-txt) of the site and follow it: it says which pages programs may read.\n",
    "- We wait between requests: arXiv asks for 15 seconds, and a class that shares one address counts as one visitor.\n",
    "- We say who we are: a request can carry a name and a way to reach us ([Reading pages responsibly](#reading-pages-responsibly) shows how).\n",
    "- We take only what the task needs, and no personal data.\n",
    "\n",
    "## A page is text with tags\n",
    "\n",
    "When we type an address in the browser, the browser sends a **request** to the **server** that holds the page, and the server sends back a **response**. The exchange follows the rules of **[HTTP](https://dvirross.com/courses/intro-data-science/glossary#http)**, the way of talking of the web, and the address is a **[URL](https://dvirross.com/courses/intro-data-science/glossary#url)**. The response holds the text of the page, written in **[HTML](https://dvirross.com/courses/intro-data-science/glossary#html)**: text wrapped in **tags**, words in angle brackets such as `<dt>` and `</dt>`, which tell the browser what each piece is. The browser hides the tags and draws the page. A program that asks for the page receives the tags too.\n",
    "\n",
    "The page is built of **elements**. An element is a piece of the page between an opening tag and a closing tag, and it can hold text and other elements. Here is the beginning of the first entry of the list, as it is in the text of the page, with parts left out:\n",
    "\n",
    "```html\n",
    "<dt><a name='item1'>[1]</a>\n",
    "  <a href=\"/abs/2610.00106\" title=\"Abstract\">arXiv:2610.00106</a>\n",
    "<dd>\n",
    "  <div class='meta'>\n",
    "    <div class='list-title mathjax'><span class='descriptor'>Title:</span>\n",
    "      SyntheticHLS: Building Diverse Synthetic High-Level ...\n",
    "    </div>\n",
    "    <div class='list-authors'>\n",
    "      <a href=\"https://arxiv.org/search/...\">Stefan Abi-Karam</a>, ...\n",
    "    </div>\n",
    "```\n",
    "\n",
    "- **Nesting.** The element `dd` holds the `div` of the class `meta`, which holds the `div` of the title, which holds a `span`. The inner elements are the **children** of the outer one.\n",
    "- **Attributes.** An opening tag may carry attributes, pairs of a name and a value such as `href=\"/abs/2610.00106\"` or `title=\"Abstract\"`. The text of an element is what a reader sees; an attribute is information about the element, for example where a link goes.\n",
    "- **Class.** The attribute `class` gives an element one or more names, here `list-title` and `mathjax`. Elements of the same kind share a class name, so the class is how a program tells a title from a line of authors.\n",
    "\n",
    "The browser shows the elements of the page as a tree. A right click on a part of the page and the item **Inspect** open the developer tools, with the clicked element marked. When we want data from a page, this look decides what to write in code: which tag holds it, which class or attribute tells it from the elements around it, and whether we need its text or an attribute.\n",
    "\n",
    "<figure class=\"lesson-shot\">\n",
    "<a href=\"/images/course-illustrations/data-collection/arxiv-devtools-entry.webp\"><img src=\"/images/course-illustrations/data-collection/arxiv-devtools-entry.webp\" width=\"773\" height=\"462\" alt=\"The developer tools of a browser on the arXiv list, with the elements tree open on the first entry. Four numbered markers highlight the opening tag of an element, its class attribute, its text, and the href attribute of a link.\" loading=\"lazy\"></a>\n",
    "<figcaption>The elements tree of the first entry. Marker 1: a tag, the name of the element. Marker 2: the attribute <code>class</code>, which tells what kind of element it is. Marker 3: the text that the element holds, the title of the paper. Marker 4: the attribute <code>href</code> of a link, the address it leads to.</figcaption>\n",
    "</figure>\n",
    "\n",
    "## Asking for the page from Python\n",
    "\n",
    "The library `requests` sends a request from Python. The first line of the next box imports it. The function `requests.get` sends a request that asks for a page, and returns a **response object**: everything that came back, kept in one variable. Two things in it are read first: `status_code`, a number that says how the request went (200 means that the page arrived), and `text`, the text of the page as one long string. The function `len` returns the number of characters of a string. The address is long, so it is written in two parts: two texts in quotes that stand next to each other, inside brackets, are joined by Python into one text, and the brackets let them go on in the next line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c010",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.012940Z",
     "iopub.status.busy": "2026-11-22T13:17:22.012738Z",
     "iopub.status.idle": "2026-11-22T13:17:22.020062Z",
     "shell.execute_reply": "2026-11-22T13:17:22.019104Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "200\n",
      "46598\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "list_url = (\n",
    "    'https://dvirross.com/materials/courses/'\n",
    "    'intro-data-science/arxiv-cs-ar-2026-10.htm'\n",
    ")\n",
    "response = requests.get(list_url)\n",
    "print(response.status_code)\n",
    "html = response.text\n",
    "print(len(html))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c011",
   "metadata": {},
   "source": [
    "The page is 46,598 characters long, much more than what we see on the screen, because most of it is tags.\n",
    "\n",
    "## Beautiful Soup reads the tags\n",
    "\n",
    "**Beautiful Soup** is a Python library that reads the text of an HTML page and builds from it the tree of its elements, so that we can ask for an element instead of cutting text. A program that reads text in a given format and builds a structure from it is a **[parser](https://dvirross.com/courses/intro-data-science/glossary#parser)**. The library `beautifulsoup4` is imported under the name `bs4`, and the class that we use is `BeautifulSoup`. It takes two arguments: the text of the page, and the name of the parser, `'html.parser'`, the one that comes with Python.\n",
    "\n",
    "<p><small>The name comes from the song \"Beautiful Soup\" that the Mock Turtle sings in Lewis Carroll's <em>Alice's Adventures in Wonderland</em>. It also plays on \"tag soup\", the name for HTML that is messy and badly structured, which is the kind of page the library was made to read.</small></p>\n",
    "\n",
    "Two more names are needed. `soup.title` is the first element of the tag `title` in the page, and the name `text` written after an element, as in `soup.title.text`, gives all the text inside it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c012",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.022086Z",
     "iopub.status.busy": "2026-11-22T13:17:22.021911Z",
     "iopub.status.idle": "2026-11-22T13:17:22.061646Z",
     "shell.execute_reply": "2026-11-22T13:17:22.060563Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<title>Hardware Architecture Oct 2026</title>\n",
      "Hardware Architecture Oct 2026\n"
     ]
    }
   ],
   "source": [
    "from bs4 import BeautifulSoup\n",
    "\n",
    "soup = BeautifulSoup(html, 'html.parser')\n",
    "print(soup.title)\n",
    "print(soup.title.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c013",
   "metadata": {},
   "source": [
    "The first line printed the element with its tags, and the second only the text that it holds.\n",
    "\n",
    "## `find`: the first element that fits\n",
    "\n",
    "The method `find` of the soup returns the first element that fits what we ask. We give it the name of a tag, and, to tell elements of the same tag apart, a class. The word `class` is a reserved word of Python, so the argument is written `class_`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c014",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.063821Z",
     "iopub.status.busy": "2026-11-22T13:17:22.063622Z",
     "iopub.status.idle": "2026-11-22T13:17:22.067816Z",
     "shell.execute_reply": "2026-11-22T13:17:22.066556Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Title:\n",
      "          SyntheticHLS: Building Diverse Synthetic High-Level Synthesis Datasets using LLMs\n",
      "        \n"
     ]
    }
   ],
   "source": [
    "title = soup.find('div', class_='list-title')\n",
    "print(title.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c015",
   "metadata": {},
   "source": [
    "The text of the element is what the title holds, with its inner element: the word `Title:` of the span, and the spaces and the line breaks of the page around the title. Two string methods clean it. `replace('Title:', '')` replaces a piece of text with another one, here with nothing, and `strip()` removes the spaces and the line breaks from both ends of a string."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c016",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.069760Z",
     "iopub.status.busy": "2026-11-22T13:17:22.069377Z",
     "iopub.status.idle": "2026-11-22T13:17:22.073195Z",
     "shell.execute_reply": "2026-11-22T13:17:22.072218Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SyntheticHLS: Building Diverse Synthetic High-Level Synthesis Datasets using LLMs\n"
     ]
    }
   ],
   "source": [
    "print(title.text.replace('Title:', '').strip())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c017",
   "metadata": {},
   "source": [
    "**Your turn.** What does `find` return when no element fits? Predict what the box prints, then run it. This page has no element of the tag `table`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c018",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.074974Z",
     "iopub.status.busy": "2026-11-22T13:17:22.074812Z",
     "iopub.status.idle": "2026-11-22T13:17:22.078677Z",
     "shell.execute_reply": "2026-11-22T13:17:22.077771Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "print(soup.find('table'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c019",
   "metadata": {},
   "source": [
    "## An attribute is read with `get`\n",
    "\n",
    "The link to the page of the first paper is not text on the screen: it is the attribute `href` of an element `a`. The method `get` of an element returns the value of one attribute, given by name. To find the element, `find` accepts any attribute as an argument: the element `a` whose attribute `title` is `Abstract`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c020",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.080510Z",
     "iopub.status.busy": "2026-11-22T13:17:22.080357Z",
     "iopub.status.idle": "2026-11-22T13:17:22.084941Z",
     "shell.execute_reply": "2026-11-22T13:17:22.082656Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "arXiv:2610.00106\n",
      "/abs/2610.00106\n"
     ]
    }
   ],
   "source": [
    "link = soup.find('a', title='Abstract')\n",
    "print(link.text.strip())\n",
    "print(link.get('href'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c021",
   "metadata": {},
   "source": [
    "The text of the link is what a reader sees, the identifier of the paper; its attribute `href` is where the link goes. The address starts with a slash and has no site name: it is relative to the site of the page, which is `https://arxiv.org`, so the page of this paper is `https://arxiv.org/abs/2610.00106`.\n",
    "\n",
    "So far we gave the attribute as an argument, like `title='Abstract'`, which fits `<a title=\"Abstract\">`. That works as long as the name of the attribute is not the name of a parameter of `find`. At the top of the first entry there is the element `<a name=\"item1\">[1]</a>`, and its attribute is called `name`. The first parameter of `find` is also called `name`, and it is the name of the tag, so `find('a', name='item1')` raises a `TypeError`. The argument `attrs` writes the condition on the attribute as a dictionary, and it works for every attribute. We use it when the attribute is called `name`, or when its name is not valid as an argument, such as `data-id` (`class` also has the form `class_`). The anchor `item1` is found like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c022",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.086523Z",
     "iopub.status.busy": "2026-11-22T13:17:22.086347Z",
     "iopub.status.idle": "2026-11-22T13:17:22.089945Z",
     "shell.execute_reply": "2026-11-22T13:17:22.088909Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1]\n"
     ]
    }
   ],
   "source": [
    "anchor = soup.find('a', attrs={'name': 'item1'})\n",
    "print(anchor.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c023",
   "metadata": {},
   "source": [
    "## Moving inside an element\n",
    "\n",
    "An element that `find` returned has a `find` of its own, which looks only inside it. This is how we narrow the search: first the entry, then the part of the entry. The first element `dt` of the page is the line with the identifier of the paper. Its first link, `dt.a`, is a link that has no `href`: look at what `get` returns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c024",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.091867Z",
     "iopub.status.busy": "2026-11-22T13:17:22.091695Z",
     "iopub.status.idle": "2026-11-22T13:17:22.095700Z",
     "shell.execute_reply": "2026-11-22T13:17:22.094402Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<a name=\"item1\">[1]</a>\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "entry = soup.find('dt')\n",
    "print(entry.a)\n",
    "print(entry.a.get('href'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c025",
   "metadata": {},
   "source": [
    "The first `a` in the entry is the anchor `[1]`, with the attribute `name`, which the page uses for its own jumps. It has no `href`, so `get` returns `None` and does not fail. The entry holds more links, and the link that we want is the one with `title='Abstract'`. Reading by position, \"the first link\", is the weak point of a program; reading by what the element is, its class or its attribute, is the strong one.\n",
    "\n",
    "The elements inside an element can also be reached by their tag name, one level after the other, with dots: `first.div` is the first `div` inside the entry `first`, and `.div` again is the first `div` inside it, which here is the title. The method `get_text` returns the text of an element like `text` does, and takes arguments: `get_text(' ', strip=True)` joins the pieces of the text with a space and removes the spaces at the two ends."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c026",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.097703Z",
     "iopub.status.busy": "2026-11-22T13:17:22.097520Z",
     "iopub.status.idle": "2026-11-22T13:17:22.101183Z",
     "shell.execute_reply": "2026-11-22T13:17:22.100286Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Title: SyntheticHLS: Building Diverse Synthetic High-Level Synthesis Datasets using LLMs\n"
     ]
    }
   ],
   "source": [
    "first = soup.find('dd')\n",
    "print(first.div.div.get_text(' ', strip=True))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c027",
   "metadata": {},
   "source": [
    "The path `first.div.div` depends on the place of each element, so it breaks when the page adds a `div` before the title. Reading by `class_` does not.\n",
    "\n",
    "### Practice\n",
    "\n",
    "**Your turn.** Print the title of the first paper of the list, without the word `Title:` and without the spaces around it, as one line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c028",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.103172Z",
     "iopub.status.busy": "2026-11-22T13:17:22.102994Z",
     "iopub.status.idle": "2026-11-22T13:17:22.106525Z",
     "shell.execute_reply": "2026-11-22T13:17:22.104991Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c029",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "SyntheticHLS: Building Diverse Synthetic High-Level Synthesis Datasets using LLMs\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c030",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.108106Z",
     "iopub.status.busy": "2026-11-22T13:17:22.107932Z",
     "iopub.status.idle": "2026-11-22T13:17:22.111380Z",
     "shell.execute_reply": "2026-11-22T13:17:22.110151Z"
    }
   },
   "outputs": [],
   "source": [
    "check(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c031",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> The title is in the `div` of the class `list-title`. Take its `text`, remove `'Title:'` with `replace`, and clean the ends with `strip`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c032",
   "metadata": {},
   "source": [
    "**Your turn.** The pdf of the first paper is a link with the attribute `title` equal to `Download PDF`. Print the address in its attribute `href`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c033",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.113573Z",
     "iopub.status.busy": "2026-11-22T13:17:22.113403Z",
     "iopub.status.idle": "2026-11-22T13:17:22.117288Z",
     "shell.execute_reply": "2026-11-22T13:17:22.116065Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c034",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "/pdf/<number>.<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c035",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.119182Z",
     "iopub.status.busy": "2026-11-22T13:17:22.119005Z",
     "iopub.status.idle": "2026-11-22T13:17:22.122568Z",
     "shell.execute_reply": "2026-11-22T13:17:22.121313Z"
    }
   },
   "outputs": [],
   "source": [
    "check(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c036",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> As in the link to the abstract, `find('a', title='Download PDF')` returns the element, and `get('href')` returns the address."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c037",
   "metadata": {},
   "source": [
    "**Your turn.** The subject of a paper is in a `span` of the class `primary-subject`. Print the text of that element for the first paper of the list."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c038",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.124152Z",
     "iopub.status.busy": "2026-11-22T13:17:22.124002Z",
     "iopub.status.idle": "2026-11-22T13:17:22.127156Z",
     "shell.execute_reply": "2026-11-22T13:17:22.126069Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c039",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "Hardware Architecture (cs.AR)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c040",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.128958Z",
     "iopub.status.busy": "2026-11-22T13:17:22.128781Z",
     "iopub.status.idle": "2026-11-22T13:17:22.132078Z",
     "shell.execute_reply": "2026-11-22T13:17:22.131118Z"
    }
   },
   "outputs": [],
   "source": [
    "check(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c041",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> `find('span', class_='primary-subject')` returns the first element of the page that fits, which is the one of the first paper."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c042",
   "metadata": {},
   "source": [
    "## Keep in mind\n",
    "\n",
    "- An element has a tag, attributes and content, and can hold other elements. The attribute `class` tells what kind of element it is; the attribute `href` of a link is where it leads.\n",
    "- `BeautifulSoup(html, 'html.parser')` builds the tree of the elements from the text of the page.\n",
    "- `soup.find(tag, class_=name)` returns the first element that fits, or `None`; `find` also takes any attribute as an argument (`title='Abstract'`) or a dictionary `attrs`.\n",
    "- `text` of an element is its text, `get('name')` is the value of an attribute, and `get` returns `None` when the attribute is missing.\n",
    "- `replace` and `strip` clean text; an element has a `find` of its own that looks only inside it.\n",
    "- Read by what the element is (class, attribute), not by its place in the page."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c043",
   "metadata": {},
   "source": [
    "**Live site.** The cell below can ask arXiv itself for the first 25 entries of October 2026, with a user agent that says how to reach us. It is switched off (`RUN_LIVE = False`): a whole class that runs it together sends many requests from one address, and arXiv asks programs to wait 15 seconds between requests. One person, once, can set `RUN_LIVE = True` to see the live site. The rest of the notebook works on the saved copy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c044",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.134035Z",
     "iopub.status.busy": "2026-11-22T13:17:22.133859Z",
     "iopub.status.idle": "2026-11-22T13:17:22.137655Z",
     "shell.execute_reply": "2026-11-22T13:17:22.136673Z"
    }
   },
   "outputs": [],
   "source": [
    "RUN_LIVE = False  # switch to True to ask arXiv itself (one request)\n",
    "if RUN_LIVE:\n",
    "    live_headers = {'User-Agent': 'IntroDataScienceCourse/1.0 (teaching example; contact via dvirross.com)'}\n",
    "    live = requests.get('https://arxiv.org/list/cs.AR/2026-10?skip=0&show=25', headers=live_headers, timeout=30)\n",
    "    if live.status_code in (403, 429):\n",
    "        print('The site refused the request or asked to slow down (status', live.status_code, '). Do not try again now; wait and use the saved copy.')\n",
    "    else:\n",
    "        print(live.status_code, len(live.text), live.text.count('<dt>'))\n",
    "else:\n",
    "    print('The live cell is off. Set RUN_LIVE = True to run it.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c045",
   "metadata": {},
   "source": [
    "> **Self-study, importance 1.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Reading pages responsibly. It helps with: reading a site responsibly (robots.txt, request rate, who we are)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c046",
   "metadata": {},
   "source": [
    "## Reading pages responsibly\n",
    "\n",
    "A program that reads a site is a guest. A few rules keep it a welcome one.\n",
    "\n",
    "- **`robots.txt`.** Every site may publish a file with this name at its top address, in which it asks programs which pages not to read and how fast to read the others. It is a request that careful programs keep, not a lock. A saved copy of the file of arXiv is kept on this site, and the box below prints the first lines of its first group: `split('User-agent:')` cuts the text at each group, and `splitlines()` returns the text of a group as a list of lines.\n",
    "- **Rate.** The line `Crawl-delay: 15` asks for 15 seconds between two requests. A program that sends requests one after the other without a pause could slow the site for its readers, and would be blocked. In code the pause is one line, `time.sleep(15)`, which stops the program for 15 seconds.\n",
    "- **Who is asking.** Every request carries the name of the program that sends it, the **[user agent](https://dvirross.com/courses/intro-data-science/glossary#user-agent)**. The library `requests` sends the name `python-requests` unless we change it, and some sites refuse that name: on 13 November 2026 the English Wikipedia answers it with the status code 403. A polite program sends a name of its own that says what it is and how to reach its owner, in the argument `headers` of `requests.get`.\n",
    "- **Terms of use and rights.** The papers belong to their authors, and the terms of a site say what may be copied and where it may be shown. The copy of the pages on this site is for teaching, and it is not a copy for another site.\n",
    "- **Personal data.** The page of a paper shows the name of the person who submitted it. The questions of these lessons do not need it, so the programs do not read it. Collect what the question needs, and think twice before building a table of people.\n",
    "- **A better door.** When a site offers its data through an API, the interface made for programs, that is the polite way to ask for a lot of data. arXiv documents one for large collections."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c047",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.139404Z",
     "iopub.status.busy": "2026-11-22T13:17:22.139180Z",
     "iopub.status.idle": "2026-11-22T13:17:22.144223Z",
     "shell.execute_reply": "2026-11-22T13:17:22.143106Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "*\n",
      "Crawl-delay: 15\n",
      "Allow: /archive\n",
      "Allow: /year\n",
      "Allow: /list\n"
     ]
    }
   ],
   "source": [
    "robots_url = (\n",
    "    'https://dvirross.com/materials/courses/'\n",
    "    'intro-data-science/arxiv-robots.txt'\n",
    ")\n",
    "robots = requests.get(robots_url).text\n",
    "first_group = robots.split('User-agent:')[1]\n",
    "for line in first_group.splitlines()[:5]:\n",
    "    print(line.strip())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c048",
   "metadata": {},
   "source": [
    "A request on the live site, with a user agent of its own and the pause between requests, looks like this:\n",
    "\n",
    "```python\n",
    "import time\n",
    "\n",
    "headers = {'User-Agent': 'IntroDataScienceCourse/1.0 (teaching example; contact via dvirross.com)'}\n",
    "for address in addresses:\n",
    "    page = requests.get(address, headers=headers)\n",
    "    time.sleep(15)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c049",
   "metadata": {},
   "source": [
    "> **Self-study, importance 2.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Status codes and headers. It helps with: checking that a request succeeded."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c050",
   "metadata": {},
   "source": [
    "## Status codes and headers\n",
    "\n",
    "A server answers every request with a **[status code](https://dvirross.com/courses/intro-data-science/glossary#status-code)**, and a program checks it before it uses the text. A request for a page that does not exist does not fail in Python: it returns a response whose code is 404.\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| 200 | The page arrived |\n",
    "| 403 | The server refuses this request |\n",
    "| 404 | There is no such page |\n",
    "| 429 | Too many requests: wait |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c051",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.145790Z",
     "iopub.status.busy": "2026-11-22T13:17:22.145623Z",
     "iopub.status.idle": "2026-11-22T13:17:22.150562Z",
     "shell.execute_reply": "2026-11-22T13:17:22.149299Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "404\n",
      "text/html; charset=utf-8\n"
     ]
    }
   ],
   "source": [
    "missing_url = (\n",
    "    'https://dvirross.com/materials/courses/'\n",
    "    'intro-data-science/arxiv-no-such-page.htm'\n",
    ")\n",
    "missing = requests.get(missing_url)\n",
    "print(missing.status_code)\n",
    "print(response.headers['Content-Type'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c052",
   "metadata": {},
   "source": [
    "The response also carries `headers`, a dictionary of information about the answer. `Content-Type` says the kind of the content, and the text encoding that the server used."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c053",
   "metadata": {},
   "source": [
    "> **Self-study, importance 3.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Text and its encoding. It helps with: text with letters outside the English alphabet."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c054",
   "metadata": {},
   "source": [
    "## Text and bytes: the encoding\n",
    "\n",
    "The response holds the page twice: `text` is a string of characters, and `content` is the bytes that the server sent. Characters that are not in the English alphabet, such as a letter with an accent in the name of an author, take two or more bytes, so the bytes are more than the characters. The library turns the bytes into text with the encoding that the server declared in `Content-Type`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c055",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.152655Z",
     "iopub.status.busy": "2026-11-22T13:17:22.152461Z",
     "iopub.status.idle": "2026-11-22T13:17:22.155909Z",
     "shell.execute_reply": "2026-11-22T13:17:22.154834Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "46598\n",
      "46606\n"
     ]
    }
   ],
   "source": [
    "print(len(response.text))\n",
    "print(len(response.content))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c056",
   "metadata": {},
   "source": [
    "When a server does not declare the encoding, the text of such a character can come out wrong. Then the bytes are decoded by hand: `response.content.decode('utf-8')`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c057",
   "metadata": {},
   "source": [
    "# Part 2: From One Element to All Entries: find_all, Numbers and Missing Values\n",
    "\n",
    "The lesson page of this part: [From One Element to All Entries: find_all, Numbers and Missing Values](https://dvirross.com/courses/intro-data-science/data-collection-find-all)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c058",
   "metadata": {},
   "source": [
    "In this lesson we learn how Beautiful Soup collects all the elements that fit, how a list comprehension turns them into data, how text that holds a number is converted to a number, and what to do when an element is missing from some of the entries.\n",
    "\n",
    "## Which paper has the most authors?\n",
    "\n",
    "Papers in hardware architecture are often the work of a team: some have one author and some have ten. On the arXiv list of October 2026 we ask how many authors a paper has, which paper has the most, and how many there are on average. The saved copy of the list holds the first 25 of its 266 entries, so the answers describe these 25 papers and not the whole month.\n",
    "\n",
    "The first box requests the saved copy of the list and builds the soup, as in [From a Web Page to Data: Beautiful Soup](https://dvirross.com/courses/intro-data-science/data-collection-beautifulsoup), so that this page stands on its own."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c059",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.157462Z",
     "iopub.status.busy": "2026-11-22T13:17:22.157318Z",
     "iopub.status.idle": "2026-11-22T13:17:22.175669Z",
     "shell.execute_reply": "2026-11-22T13:17:22.174642Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hardware Architecture Oct 2026\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "\n",
    "list_url = (\n",
    "    'https://dvirross.com/materials/courses/'\n",
    "    'intro-data-science/arxiv-cs-ar-2026-10.htm'\n",
    ")\n",
    "page_text = requests.get(list_url).text\n",
    "soup = BeautifulSoup(page_text, 'html.parser')\n",
    "print(soup.title.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c060",
   "metadata": {},
   "source": [
    "## `find_all`: every element that fits\n",
    "\n",
    "Each paper of the list is a `dd` element that holds its title, its authors and its subjects. The method `find_all` returns all the elements that fit, as a list, in the order of the page. It takes the same arguments as `find`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c061",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.177629Z",
     "iopub.status.busy": "2026-11-22T13:17:22.177456Z",
     "iopub.status.idle": "2026-11-22T13:17:22.181192Z",
     "shell.execute_reply": "2026-11-22T13:17:22.180243Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "25\n"
     ]
    }
   ],
   "source": [
    "entries = soup.find_all('dd')\n",
    "print(len(entries))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c062",
   "metadata": {},
   "source": [
    "The list `entries` has 25 elements, one for each paper, and each one has its own `find`, which looks only inside it. The steps that read the title of one paper go into a function, `title_of`. A list comprehension builds a list from another list in one line: the expression before `for` is computed for every element, here the call of `title_of`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "c063",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.182835Z",
     "iopub.status.busy": "2026-11-22T13:17:22.182686Z",
     "iopub.status.idle": "2026-11-22T13:17:22.186930Z",
     "shell.execute_reply": "2026-11-22T13:17:22.186041Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "25\n",
      "SyntheticHLS: Building Diverse Synthetic High-Level Synthesis Datasets using LLMs\n",
      "ShatterQuant: Breaking Uniform Precision with Block-Wise Mixed-Precision on a Systolic Transformer Hardware Accelerator\n"
     ]
    }
   ],
   "source": [
    "def title_of(entry):\n",
    "    box = entry.find('div', class_='list-title')\n",
    "    return box.text.replace('Title:', '').strip()\n",
    "\n",
    "titles = [title_of(entry) for entry in entries]\n",
    "print(len(titles))\n",
    "print(titles[0])\n",
    "print(titles[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c064",
   "metadata": {},
   "source": [
    "## Counting the authors\n",
    "\n",
    "The authors of a paper are in a `div` of the class `list-authors`, and each author is a link, an element `a`. So the number of authors is the number of links inside that `div`: `find_all` returns a list and `len` counts it. Run the box and look at the result for the second paper, `entries[1]`: the number of links in its `list-authors`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "c065",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.188405Z",
     "iopub.status.busy": "2026-11-22T13:17:22.188263Z",
     "iopub.status.idle": "2026-11-22T13:17:22.191745Z",
     "shell.execute_reply": "2026-11-22T13:17:22.190744Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "authors = entries[1].find('div', class_='list-authors')\n",
    "print(len(authors.find_all('a')))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c066",
   "metadata": {},
   "source": [
    "The steps that read one paper are the same for all papers, so we put them in a function, which returns the pair of the title and the number of authors, and call it on every entry. A pair like this is a tuple."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "c067",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.193409Z",
     "iopub.status.busy": "2026-11-22T13:17:22.193097Z",
     "iopub.status.idle": "2026-11-22T13:17:22.198488Z",
     "shell.execute_reply": "2026-11-22T13:17:22.197131Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('SyntheticHLS: Building Diverse Synthetic High-Level Synthesis Datasets using LLMs', 3)\n"
     ]
    }
   ],
   "source": [
    "def read_entry(entry):\n",
    "    authors = entry.find('div', class_='list-authors')\n",
    "    return (title_of(entry), len(authors.find_all('a')))\n",
    "\n",
    "papers = [read_entry(entry) for entry in entries]\n",
    "print(papers[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c068",
   "metadata": {},
   "source": [
    "> **Self-study, importance 1.** This part is for self-study: it is not taught in the lecture, and you read it on your own. The maximum of a list of pairs and the mean of a list of numbers. It helps with: maximum and average over a list of scraped values."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c069",
   "metadata": {},
   "source": [
    "## The maximum and the mean\n",
    "\n",
    "`papers` is a list of 25 pairs. The function `max` returns the largest item, and its argument `key` says what to compare: here a function that takes a pair and returns its second part, the number of authors, written as `lambda paper: paper[1]`. The mean is the sum divided by the count, and `round(number, 2)` keeps two digits after the decimal point."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "c070",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.200877Z",
     "iopub.status.busy": "2026-11-22T13:17:22.200711Z",
     "iopub.status.idle": "2026-11-22T13:17:22.204366Z",
     "shell.execute_reply": "2026-11-22T13:17:22.203427Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 PEEK: Heterogeneous Parallelism for Privileged Error Detection in Safety-Critical Processors\n",
      "4.2\n"
     ]
    }
   ],
   "source": [
    "top = max(papers, key=lambda paper: paper[1])\n",
    "print(top[1], top[0])\n",
    "\n",
    "counts = [paper[1] for paper in papers]\n",
    "print(round(sum(counts) / len(counts), 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c071",
   "metadata": {},
   "source": [
    "Among these 25 papers the largest team has 10 authors, and the mean is 4.2 authors per paper. The mean is higher than a typical paper: half of the papers have 4 authors or fewer, and a few large teams raise the mean.\n",
    "\n",
    "## Text that holds a number\n",
    "\n",
    "The page says how many entries the month has, in the line `Total of 266 entries`, in a `div` of the class `paging`. The text is not a number, and a program cannot compute with it. The method `split()` cuts a text at its spaces and returns a list of its words; `[2]`, the third word, counted from 0, is `'266'`, and the function `int` converts the text of a whole number to a number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "c072",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.206696Z",
     "iopub.status.busy": "2026-11-22T13:17:22.206522Z",
     "iopub.status.idle": "2026-11-22T13:17:22.210154Z",
     "shell.execute_reply": "2026-11-22T13:17:22.209183Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "266\n",
      "25 of 266\n"
     ]
    }
   ],
   "source": [
    "paging = soup.find('div', class_='paging')\n",
    "total = int(paging.text.split()[2])\n",
    "print(total)\n",
    "print(len(entries), 'of', total)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c073",
   "metadata": {},
   "source": [
    "Without `int`, the program would hold the text `'266'`, and `'266' + 1` would be an error. A number written with a thousands separator, such as `3,330`, needs one more step, which is `replace(',', '')`, because `int` does not read the comma.\n",
    "\n",
    "A number with a decimal point is converted with `float`, and a unit written after it is removed first. The page of a paper writes the size of its submission as `3,330 KB`, and the same steps give the number:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "c074",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.211518Z",
     "iopub.status.busy": "2026-11-22T13:17:22.211372Z",
     "iopub.status.idle": "2026-11-22T13:17:22.214900Z",
     "shell.execute_reply": "2026-11-22T13:17:22.213749Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3330.0\n"
     ]
    }
   ],
   "source": [
    "size_text = '3,330 KB'\n",
    "number = size_text.replace(' KB', '').replace(',', '')\n",
    "print(float(number))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c075",
   "metadata": {},
   "source": [
    "## An element that is missing\n",
    "\n",
    "Not every paper has the line of comments, in which the authors write, for example, the number of pages. In the list, 13 of the 25 papers have no `div` of the class `list-comments` at all. For such an entry `find` returns `None`, and `None.text` is an error. A program that reads many entries tests for `None` before it reads."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "c076",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.216696Z",
     "iopub.status.busy": "2026-11-22T13:17:22.216537Z",
     "iopub.status.idle": "2026-11-22T13:17:22.220819Z",
     "shell.execute_reply": "2026-11-22T13:17:22.219838Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "13\n"
     ]
    }
   ],
   "source": [
    "without_comments = [\n",
    "    entry for entry in entries\n",
    "    if entry.find('div', class_='list-comments') is None\n",
    "]\n",
    "print(len(without_comments))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c077",
   "metadata": {},
   "source": [
    "When the comments exist, they are free text written by the authors, such as `7 pages, 5 figures. Accepted to ASP-DAC 2027`. A program reads a number of pages only where the text says it, in the form that a number comes first and the word `pages` after it. The method `isdigit()` tells whether a text is made of digits only, and `startswith('pages')` whether a text begins with the word. The function returns `None` for every entry that does not say."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "c078",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.222326Z",
     "iopub.status.busy": "2026-11-22T13:17:22.222151Z",
     "iopub.status.idle": "2026-11-22T13:17:22.225697Z",
     "shell.execute_reply": "2026-11-22T13:17:22.224501Z"
    }
   },
   "outputs": [],
   "source": [
    "def pages_of(entry):\n",
    "    box = entry.find('div', class_='list-comments')\n",
    "    if box is None:\n",
    "        return None\n",
    "    words = box.text.replace('Comments:', '').split()\n",
    "    if len(words) < 2:\n",
    "        return None\n",
    "    if words[0].isdigit() and words[1].startswith('pages'):\n",
    "        return int(words[0])\n",
    "    return None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "c079",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.227441Z",
     "iopub.status.busy": "2026-11-22T13:17:22.227282Z",
     "iopub.status.idle": "2026-11-22T13:17:22.231841Z",
     "shell.execute_reply": "2026-11-22T13:17:22.230554Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[None, None, 7, None, 4, 4, None, None, None, None, 8, None, None, None, 10, 15, None, None, None, None, None, None, None, None, None]\n"
     ]
    }
   ],
   "source": [
    "all_pages = [pages_of(entry) for entry in entries]\n",
    "print(all_pages)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c080",
   "metadata": {},
   "source": [
    "A missing number is not zero. To compute with the numbers that exist, we keep only the items that are not `None`, and the mean is over those:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "c081",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.233712Z",
     "iopub.status.busy": "2026-11-22T13:17:22.233540Z",
     "iopub.status.idle": "2026-11-22T13:17:22.237113Z",
     "shell.execute_reply": "2026-11-22T13:17:22.236150Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6 15 8.0\n"
     ]
    }
   ],
   "source": [
    "known = [pages for pages in all_pages if pages is not None]\n",
    "print(len(known), max(known), sum(known) / len(known))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c082",
   "metadata": {},
   "source": [
    "Only 6 of the 25 papers say how many pages they have, and these 6 have 8 pages on average and at most 15. The number describes the papers that say, which may be different from the papers that do not.\n",
    "\n",
    "### Practice\n",
    "\n",
    "**Your turn.** The list `papers` holds a pair of the title and the number of authors for each paper. Print the title of the paper that has the fewest authors; when several papers have the fewest, print the first of them in the list. The function `min` takes the same argument `key` as `max`; both appeared in [Python for Databases 2: Loops and Functions](https://dvirross.com/courses/intro-data-science/python-loops-and-functions)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "c083",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.238754Z",
     "iopub.status.busy": "2026-11-22T13:17:22.238580Z",
     "iopub.status.idle": "2026-11-22T13:17:22.241472Z",
     "shell.execute_reply": "2026-11-22T13:17:22.240440Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c084",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "A Compression Tree Generation Method for High Performance VLSI Datapaths\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "c085",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.243042Z",
     "iopub.status.busy": "2026-11-22T13:17:22.242890Z",
     "iopub.status.idle": "2026-11-22T13:17:22.246361Z",
     "shell.execute_reply": "2026-11-22T13:17:22.245216Z"
    }
   },
   "outputs": [],
   "source": [
    "check(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c086",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> The function `min` works like `max`, with the same argument `key`. It returns the first of the items that have the smallest value."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c087",
   "metadata": {},
   "source": [
    "> **Self-study, importance 2.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Two more practice tasks: counting and a mean. It helps with: counting items by a condition, and a mean that skips a missing value."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c088",
   "metadata": {},
   "source": [
    "**Your turn.** Print how many of the 25 papers have at least 5 authors, as one number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "c089",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.248309Z",
     "iopub.status.busy": "2026-11-22T13:17:22.248075Z",
     "iopub.status.idle": "2026-11-22T13:17:22.250940Z",
     "shell.execute_reply": "2026-11-22T13:17:22.249955Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c090",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "c091",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.252741Z",
     "iopub.status.busy": "2026-11-22T13:17:22.252568Z",
     "iopub.status.idle": "2026-11-22T13:17:22.256141Z",
     "shell.execute_reply": "2026-11-22T13:17:22.254946Z"
    }
   },
   "outputs": [],
   "source": [
    "check(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c092",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Build a list of the pairs whose second part is at least 5 with a condition at the end of a list comprehension, and print its length."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c093",
   "metadata": {},
   "source": [
    "**Your turn.** The function `pages_of` above returns the number of pages of an entry, or `None`. Print the mean number of pages, rounded to one digit after the decimal point, over the papers that say how many pages they have."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "c094",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.257760Z",
     "iopub.status.busy": "2026-11-22T13:17:22.257590Z",
     "iopub.status.idle": "2026-11-22T13:17:22.260502Z",
     "shell.execute_reply": "2026-11-22T13:17:22.259383Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c095",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>.<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "c096",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.262249Z",
     "iopub.status.busy": "2026-11-22T13:17:22.262081Z",
     "iopub.status.idle": "2026-11-22T13:17:22.264898Z",
     "shell.execute_reply": "2026-11-22T13:17:22.263978Z"
    }
   },
   "outputs": [],
   "source": [
    "check(6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c097",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Keep only the values that are not `None`, as in the list `known`, and divide their sum by their count, not by the number of entries."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c098",
   "metadata": {},
   "source": [
    "## Keep in mind\n",
    "\n",
    "- `find_all` returns a list of all the elements that fit; an element of the list has its own `find` and `find_all`.\n",
    "- A list comprehension turns the list of elements into a list of data; a function that reads one entry keeps the code in one place.\n",
    "- The text of an element is text: `int(...)` converts text of a whole number, `float(...)` a number with a decimal point, `split()` cuts a text into words, and a unit or a thousands separator is removed with `replace` first.\n",
    "- An element that is missing gives `None` from `find`; test `is None` before reading `text`, and keep a missing value out of a mean, because it is not zero.\n",
    "- `max` and `min` with `key` return the item with the largest or the smallest value of a part of it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c099",
   "metadata": {},
   "source": [
    "# Part 3: From a List to Many Pages: Following Links\n",
    "\n",
    "The lesson page of this part: [From a List to Many Pages: Following Links](https://dvirross.com/courses/intro-data-science/data-collection-linked-pages)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c100",
   "metadata": {},
   "source": [
    "> **Self-study.** This page is for self-study: it is not taught in the lecture, and you read it on your own."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c101",
   "metadata": {},
   "source": [
    "In this lesson we learn how a program follows the links of a list to the page of each item, reads data from the tags that describe a page, turns text such as `3,330 KB` into a number, and collects the results of many pages in one list.\n",
    "\n",
    "## How large is the submission of each paper?\n",
    "\n",
    "The list of papers shows the title, the authors and the subjects of each paper, but not the size of the files that the authors submitted. That number is on the page of each paper, which the list links to. The question is: among the first eight papers of the list, which one has the largest submission, and what is the median size? To answer it, a program has to read the list, follow eight links and read one number on each page.\n",
    "\n",
    "The first box defines `soup_of`, a function that requests an address and returns the soup of its page, as in [From a Web Page to Data: Beautiful Soup](https://dvirross.com/courses/intro-data-science/data-collection-beautifulsoup), so that this page stands on its own. It builds the soup of the list and collects the links to the papers: every link whose attribute `title` is `Abstract`, as in [From a Web Page to Data: Beautiful Soup](https://dvirross.com/courses/intro-data-science/data-collection-beautifulsoup). A slice, `[:8]`, keeps the first eight."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "c102",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.266738Z",
     "iopub.status.busy": "2026-11-22T13:17:22.266597Z",
     "iopub.status.idle": "2026-11-22T13:17:22.286215Z",
     "shell.execute_reply": "2026-11-22T13:17:22.284903Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/abs/2610.00106\n",
      "8\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "\n",
    "copies = (\n",
    "    'https://dvirross.com/materials/courses/'\n",
    "    'intro-data-science/'\n",
    ")\n",
    "\n",
    "def soup_of(address):\n",
    "    text = requests.get(address).text\n",
    "    return BeautifulSoup(text, 'html.parser')\n",
    "\n",
    "soup = soup_of(copies + 'arxiv-cs-ar-2026-10.htm')\n",
    "anchors = soup.find_all('a', title='Abstract')\n",
    "links = [a.get('href') for a in anchors][:8]\n",
    "print(links[0])\n",
    "print(len(links))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c103",
   "metadata": {},
   "source": [
    "## From the link to the address of a page\n",
    "\n",
    "The `href` of a paper is `/abs/2610.00106`: the identifier of the paper is its last part, and the address is relative to the site of the list, `https://arxiv.org`. On the live site the full address is the site name followed by the `href`. The saved copies of the papers are kept under names of the form `arxiv-abs-2610.00106.htm`, so a function turns an `href` into the address of its copy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "c104",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.287986Z",
     "iopub.status.busy": "2026-11-22T13:17:22.287829Z",
     "iopub.status.idle": "2026-11-22T13:17:22.304879Z",
     "shell.execute_reply": "2026-11-22T13:17:22.303496Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Title:SyntheticHLS: Building Diverse Synthetic High-Level Synthesis Datasets using LLMs\n"
     ]
    }
   ],
   "source": [
    "def copy_address(href):\n",
    "    paper_id = href.replace('/abs/', '')\n",
    "    return copies + 'arxiv-abs-' + paper_id + '.htm'\n",
    "\n",
    "page = soup_of(copy_address(links[0]))\n",
    "print(page.find('h1', class_='title').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c105",
   "metadata": {},
   "source": [
    "## Data in the tags that describe the page\n",
    "\n",
    "The head of every page holds `meta` elements: tags that are not drawn, which describe the page to search engines and to programs. Each has an attribute `name` that says what it holds, and an attribute `content` that holds the value, for example the date in which the paper was submitted. The first parameter of `find` is also called `name`, so writing `name='citation_date'` raises a `TypeError`; the attribute goes in the dictionary `attrs`, with the name that we want; `get('content')` reads its value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "c106",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.306506Z",
     "iopub.status.busy": "2026-11-22T13:17:22.306328Z",
     "iopub.status.idle": "2026-11-22T13:17:22.310314Z",
     "shell.execute_reply": "2026-11-22T13:17:22.308917Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026/09/09\n"
     ]
    }
   ],
   "source": [
    "date = page.find('meta', attrs={'name': 'citation_date'})\n",
    "print(date.get('content'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c107",
   "metadata": {},
   "source": [
    "The same page has one `meta` element for each author, with the name `citation_author`, so `find_all` with the same `attrs` counts the authors:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "c108",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.312500Z",
     "iopub.status.busy": "2026-11-22T13:17:22.312295Z",
     "iopub.status.idle": "2026-11-22T13:17:22.315945Z",
     "shell.execute_reply": "2026-11-22T13:17:22.315452Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "meta_name = {'name': 'citation_author'}\n",
    "print(len(page.find_all('meta', attrs=meta_name)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c109",
   "metadata": {},
   "source": [
    "## A number inside text\n",
    "\n",
    "The size of the submission is written in the section of the page called the submission history, in a `div` of the class `submission-history`, as part of a line of text: `[v1] Wed, 9 Sep 2026 02:40:29 UTC (3,330 KB)`. The number is between a bracket and the letters `KB`, and it has a comma. We take it in three steps. `split('(')` cuts the text at every opening bracket and returns a list of the pieces, and `[-1]`, the last piece, is `'3,330 KB)'` with a line break. These papers have one version each; with several versions the last piece is the size of the last one. `replace` removes the letters and the comma, `strip` removes the line break, and `int` converts the text to a number. The function `repr` shows a text as it is written, with its hidden characters, such as the line break `\\n`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "c110",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.318052Z",
     "iopub.status.busy": "2026-11-22T13:17:22.317857Z",
     "iopub.status.idle": "2026-11-22T13:17:22.322415Z",
     "shell.execute_reply": "2026-11-22T13:17:22.321132Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'3,330 KB)\\n'\n",
      "3330\n"
     ]
    }
   ],
   "source": [
    "box = page.find('div', class_='submission-history')\n",
    "history = box.text\n",
    "piece = history.split('(')[-1]\n",
    "print(repr(piece))\n",
    "number = piece.replace('KB)', '').replace(',', '')\n",
    "kb = int(number.strip())\n",
    "print(kb)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c111",
   "metadata": {},
   "source": [
    "Without the removal of the comma, `int('3,330')` raises an error.\n",
    "\n",
    "## A missing element stops the program\n",
    "\n",
    "Some papers have a line of comments in the table of the page, an element `td` of the class `comments`, and some do not. The comment of the first paper is there; the page of the second paper has none. Asking for the text of an element that is not there is an error:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c112",
   "metadata": {},
   "source": [
    "On the page of the lesson the cell above stops with an error on purpose. In the notebook the cell below prints the element that `find` returned, so that the notebook runs to the end: it is `None`, and the error comes from asking `None` for `.text`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "c113",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.324024Z",
     "iopub.status.busy": "2026-11-22T13:17:22.323858Z",
     "iopub.status.idle": "2026-11-22T13:17:22.346067Z",
     "shell.execute_reply": "2026-11-22T13:17:22.345000Z"
    }
   },
   "outputs": [],
   "source": [
    "second = soup_of(copy_address(links[1]))\n",
    "print(second.find('td', class_='comments'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c114",
   "metadata": {},
   "source": [
    "`find` returned `None`, and `None` has no attribute `text`. A function that reads a page tests the element before it reads from it, and returns `None` for the value that does not exist. The function below reads one paper and returns its data as a dictionary: the identifier, the title from the `meta` tag, the size in KB, and the comment or `None`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "c115",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.347848Z",
     "iopub.status.busy": "2026-11-22T13:17:22.347648Z",
     "iopub.status.idle": "2026-11-22T13:17:22.375225Z",
     "shell.execute_reply": "2026-11-22T13:17:22.373514Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "19279 None\n"
     ]
    }
   ],
   "source": [
    "def read_paper(href):\n",
    "    page = soup_of(copy_address(href))\n",
    "    meta = {'name': 'citation_title'}\n",
    "    title = page.find('meta', attrs=meta).get('content')\n",
    "    box = page.find('div', class_='submission-history')\n",
    "    piece = box.text.split('(')[-1]\n",
    "    number = piece.replace('KB)', '').replace(',', '')\n",
    "    kb = int(number.strip())\n",
    "    comment = page.find('td', class_='comments')\n",
    "    if comment is not None:\n",
    "        comment = comment.text.strip()\n",
    "    return {\n",
    "        'id': href.replace('/abs/', ''),\n",
    "        'title': title, 'kb': kb, 'comment': comment,\n",
    "    }\n",
    "\n",
    "second_paper = read_paper(links[1])\n",
    "print(second_paper['kb'], second_paper['comment'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c116",
   "metadata": {},
   "source": [
    "## All eight pages\n",
    "\n",
    "A `for` loop, or a list comprehension, calls the function on each link. A program that sends many requests to one site waits between them, with `time.sleep(seconds)`, as [Reading pages responsibly](https://dvirross.com/courses/intro-data-science/data-collection-beautifulsoup#reading-pages-responsibly) explains; the copies on this site are not arXiv, so the box needs no pause."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "c117",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.377499Z",
     "iopub.status.busy": "2026-11-22T13:17:22.377297Z",
     "iopub.status.idle": "2026-11-22T13:17:22.489408Z",
     "shell.execute_reply": "2026-11-22T13:17:22.488171Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2610.00106 3330\n",
      "2610.00207 19279\n",
      "2610.00311 856\n",
      "2610.01186 866\n",
      "2610.01603 492\n",
      "2610.01623 234\n",
      "2610.01867 747\n",
      "2610.01918 159\n"
     ]
    }
   ],
   "source": [
    "papers = [read_paper(href) for href in links]\n",
    "for paper in papers:\n",
    "    print(paper['id'], paper['kb'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c118",
   "metadata": {},
   "source": [
    "The question of the lesson is answered by the maximum, the mean and the median of the sizes. The median is the middle of the sizes in order: `sorted` puts them in order, and with eight values it is the mean of the two middle ones, at places 3 and 4 (counted from 0)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "c119",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.491370Z",
     "iopub.status.busy": "2026-11-22T13:17:22.491108Z",
     "iopub.status.idle": "2026-11-22T13:17:22.495272Z",
     "shell.execute_reply": "2026-11-22T13:17:22.494238Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "19279 ShatterQuant: Breaking Uniform Precision\n",
      "3245\n",
      "801.5\n"
     ]
    }
   ],
   "source": [
    "sizes = [paper['kb'] for paper in papers]\n",
    "largest = max(papers, key=lambda paper: paper['kb'])\n",
    "print(largest['kb'], largest['title'][:40])\n",
    "print(round(sum(sizes) / len(sizes)))\n",
    "ordered = sorted(sizes)\n",
    "print((ordered[3] + ordered[4]) / 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c120",
   "metadata": {},
   "source": [
    "The largest submission is 19,279 KB, the mean is 3,245 KB and the median is 801.5 KB. One large paper pulls the mean up (the other seven have a mean of 955 KB) but not the median, so the median describes a typical paper.\n",
    "\n",
    "### Practice\n",
    "\n",
    "**Your turn.** The function `read_paper` and the list `papers` are above. Print how many of the eight papers have no comment on their page."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "c121",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.496767Z",
     "iopub.status.busy": "2026-11-22T13:17:22.496607Z",
     "iopub.status.idle": "2026-11-22T13:17:22.499958Z",
     "shell.execute_reply": "2026-11-22T13:17:22.498847Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c122",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "3\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "c123",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.502322Z",
     "iopub.status.busy": "2026-11-22T13:17:22.502123Z",
     "iopub.status.idle": "2026-11-22T13:17:22.505624Z",
     "shell.execute_reply": "2026-11-22T13:17:22.504435Z"
    }
   },
   "outputs": [],
   "source": [
    "check(7)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c124",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> In `papers`, a paper without a comment has `None` in its key `'comment'`. Count with a list comprehension and a condition `is None`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c125",
   "metadata": {},
   "source": [
    "**Your turn.** The saved copy of the page of the paper `2610.00311` is at `copies + 'arxiv-abs-2610.00311.htm'`. Print the date of its submission, from the `meta` tag `citation_date`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "c126",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.507368Z",
     "iopub.status.busy": "2026-11-22T13:17:22.507137Z",
     "iopub.status.idle": "2026-11-22T13:17:22.510137Z",
     "shell.execute_reply": "2026-11-22T13:17:22.509147Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c127",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>/<number>/<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "c128",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.511688Z",
     "iopub.status.busy": "2026-11-22T13:17:22.511544Z",
     "iopub.status.idle": "2026-11-22T13:17:22.514917Z",
     "shell.execute_reply": "2026-11-22T13:17:22.513897Z"
    }
   },
   "outputs": [],
   "source": [
    "check(8)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c129",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Build the soup of the page, find the `meta` element with `attrs={'name': 'citation_date'}` (not `name='citation_date'`, which raises a `TypeError`) and read its attribute `content` with `get`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c130",
   "metadata": {},
   "source": [
    "**Your turn.** Print the mean size in KB of the seven papers other than the largest one, rounded to a whole number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "c131",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.516643Z",
     "iopub.status.busy": "2026-11-22T13:17:22.516488Z",
     "iopub.status.idle": "2026-11-22T13:17:22.519453Z",
     "shell.execute_reply": "2026-11-22T13:17:22.518347Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c132",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "c133",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.521302Z",
     "iopub.status.busy": "2026-11-22T13:17:22.521092Z",
     "iopub.status.idle": "2026-11-22T13:17:22.524941Z",
     "shell.execute_reply": "2026-11-22T13:17:22.523456Z"
    }
   },
   "outputs": [],
   "source": [
    "check(9)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c134",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Take the sizes in `sizes`, remove the largest with `max(sizes)` by a condition in a list comprehension, and divide the sum of the others by their count."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c135",
   "metadata": {},
   "source": [
    "**Live site.** The cell below can read the pages of the first three papers of the list from arXiv itself, with a user agent that says how to reach us and the pause that `robots.txt` asks for, 15 seconds between requests; it takes about a minute. It is switched off (`RUN_LIVE = False`): a whole class that runs it together sends many requests from one address. One person, once, can set `RUN_LIVE = True`. If the site answers 403 or 429, the cell stops and says so; it does not try again. The rest of the notebook works on the saved copies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "c136",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T13:17:22.526784Z",
     "iopub.status.busy": "2026-11-22T13:17:22.526593Z",
     "iopub.status.idle": "2026-11-22T13:17:22.530968Z",
     "shell.execute_reply": "2026-11-22T13:17:22.529862Z"
    }
   },
   "outputs": [],
   "source": [
    "import time\n",
    "RUN_LIVE = False  # switch to True to ask arXiv itself (four requests, 15 seconds apart)\n",
    "if RUN_LIVE:\n",
    "    live_headers = {'User-Agent': 'IntroDataScienceCourse/1.0 (teaching example; contact via dvirross.com)'}\n",
    "    live_list = requests.get('https://arxiv.org/list/cs.AR/2026-10?skip=0&show=25', headers=live_headers, timeout=30)\n",
    "    refused = live_list.status_code in (403, 429)\n",
    "    if not refused:\n",
    "        live_soup = BeautifulSoup(live_list.text, 'html.parser')\n",
    "        for link in live_soup.find_all('a', title='Abstract')[:3]:\n",
    "            if not refused:\n",
    "                time.sleep(15)\n",
    "                live_page = requests.get('https://arxiv.org' + link.get('href'), headers=live_headers, timeout=30)\n",
    "                print(live_page.status_code, link.get('href'))\n",
    "                refused = live_page.status_code in (403, 429)\n",
    "    if refused:\n",
    "        print('The site refused a request or asked to slow down (status 403 or 429). Do not try again now; wait and use the saved copies.')\n",
    "else:\n",
    "    print('The live cell is off. Set RUN_LIVE = True to run it.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c137",
   "metadata": {},
   "source": [
    "## Keep in mind\n",
    "\n",
    "- A list page links to the page of each item; the `href` of a link is the way, and a function that turns an `href` into an address keeps the code in one place.\n",
    "- `find('meta', attrs={'name': ...})` and `get('content')` read the data that a page keeps in its `meta` tags.\n",
    "- A number inside text is cut out with `split`, cleaned with `replace` and `strip`, and converted with `int`.\n",
    "- An element that is missing is `None`; asking it for `text` raises an error, so a function tests for `None` and returns `None`.\n",
    "- The mean of a few values is pulled by a very large value; look at the maximum and the median next to the mean.\n",
    "- A program that reads a site keeps to its `robots.txt`, waits between requests, says who it is and takes only the data it needs."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "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.13.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
