{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Exploring subdomains in the whole of gov.au\n", "\n", "
New to Jupyter notebooks? Try Using Jupyter notebooks for a quick introduction.
\n", "\n", "Most of the notebooks in this repository work with small slices of web archive data. In this notebook we'll scale things up a bit to try and find all of the subdomains that have existed in the `gov.au` domain. As in other notebooks, we'll obtain the data by querying the Internet Archive's CDX API. The only real difference is that it will take some hours to harvest all the data.\n", "\n", "All we're interested in this time are unique domain names, so to minimise the amount of data we'll be harvesting we can make use of the CDX API's `collapse` parameter. By setting `collapse=urlkey` we can tell the CDX API to drop records with duplicate `urlkey` values – this should mean we only get one capture per page. However, this only works if the capture records are in adjacent rows, so there probably will still be some duplicates. We'll also use the `fl` to limit the fields returned, and the `filter` parameter to limit results by `statuscode` and `mimetype`. So the parameters we'll use are:\n", "\n", "* `url=*.gov.au` – all of the pages in all of the subdomains under `gov.au`\n", "* `collapse=urlkey` – as few captures per page as possible\n", "* `filter=statuscode:200,mimetype:text/html` – only successful captures of HTML pages\n", "* `fl=urlkey,timestamp,original` – only these fields\n", "\n", "Even with these limits, the query will retrieve a LOT of data. To make the harvesting process easier to manage and more robust, I'm going to make use of the `requests-cache` module. This will capture the results of all requests, so that if things get interrupted and we have to restart, we can retrieve already harvested requests from the cache without downloading them again. We'll also write the harvested results directly to disk rather than consuming all our computer's memory. The file format will be the NDJSON (Newline Delineated JSON) format – because each line is a separate JSON object we can just write it a line at a time as the data is received.\n", "\n", "For a general approach to harvesting domain-level information from the IA CDX API see [Harvesting data about a domain using the IA CDX API](harvesting_domain_data.ipynb)\n", "\n", "If you'd like to access pre-harvested datasets, you can download the following files from Cloudstor:\n", "\n", "* [gov-au-cdx-data-20220406105227.ndjson](https://cloudstor.aarnet.edu.au/plus/s/F3BjoCaS5U3BHCh/download?path=gov-au-cdx-data-20220406105227.ndjson) (75.7gb) – this is the raw data saved as newline delimited JSON\n", "* [gov-au-domains-split-20220406155220.csv](https://cloudstor.aarnet.edu.au/plus/s/F3BjoCaS5U3BHCh/download?path=gov-au-domains-split-20220406155220.csv) (2.4mb) – this is a CSV file containing unique domains, split into subdomains\n", "* [gov-au-unique-domains-20220406131052.csv](https://cloudstor.aarnet.edu.au/plus/s/F3BjoCaS5U3BHCh/download?path=gov-au-unique-domains-20220406131052.csv) – this is a CSV file containing unique domains in SURT format\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "import json\n", "import os\n", "import re\n", "import time\n", "from pathlib import Path\n", "\n", "import arrow\n", "import ndjson\n", "import newick\n", "import pandas as pd\n", "import requests\n", "from ete3 import Tree, TreeStyle\n", "from IPython.display import HTML, FileLink, display\n", "from newick import Node\n", "from requests.adapters import HTTPAdapter\n", "from requests.packages.urllib3.util.retry import Retry\n", "from requests_cache import CachedSession\n", "from slugify import slugify\n", "from tqdm.auto import tqdm\n", "\n", "os.environ[\"QT_QPA_PLATFORM\"] = \"offscreen\"\n", "\n", "s = CachedSession()\n", "retries = Retry(total=10, backoff_factor=1, status_forcelist=[502, 503, 504])\n", "s.mount(\"https://\", HTTPAdapter(max_retries=retries))\n", "s.mount(\"http://\", HTTPAdapter(max_retries=retries))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "domain = \"gov.au\"" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "def get_total_pages(params):\n", " \"\"\"\n", " Gets the total number of pages in a set of results.\n", " \"\"\"\n", " these_params = params.copy()\n", " these_params[\"showNumPages\"] = \"true\"\n", " response = s.get(\n", " \"http://web.archive.org/cdx/search/cdx\",\n", " params=these_params,\n", " headers={\"User-Agent\": \"\"},\n", " )\n", " return int(response.text)\n", "\n", "\n", "def prepare_params(url, **kwargs):\n", " \"\"\"\n", " Prepare the parameters for a CDX API requests.\n", " Adds all supplied keyword arguments as parameters (changing from_ to from).\n", " Adds in a few necessary parameters.\n", " \"\"\"\n", " params = kwargs\n", " params[\"url\"] = url\n", " params[\"output\"] = \"json\"\n", " # CDX accepts a 'from' parameter, but this is a reserved word in Python\n", " # Use 'from_' to pass the value to the function & here we'll change it back to 'from'.\n", " if \"from_\" in params:\n", " params[\"from\"] = params[\"from_\"]\n", " del params[\"from_\"]\n", " return params\n", "\n", "\n", "def get_cdx_data(params):\n", " \"\"\"\n", " Make a request to the CDX API using the supplied parameters.\n", " Check the results for a resumption key, and return the key (if any) and the results.\n", " \"\"\"\n", " try:\n", " response = s.get(\n", " \"http://web.archive.org/cdx/search/cdx\", params=params, timeout=120\n", " )\n", " # Some pages generate errors -- seems to be a problem at server end, so we'll ignore.\n", " # This could mean some data is lost?\n", " except requests.exceptions.ChunkedEncodingError:\n", " print(f'Error page {params[\"page\"]}')\n", " return None\n", " else:\n", " response.raise_for_status()\n", " results = response.json()\n", " if not response.from_cache:\n", " time.sleep(0.2)\n", " return results\n", "\n", "\n", "def convert_lists_to_dicts(results):\n", " if results:\n", " keys = results[0]\n", " results_as_dicts = [dict(zip(keys, v)) for v in results[1:]]\n", " else:\n", " results_as_dicts = results\n", " return results_as_dicts\n", "\n", "\n", "def get_cdx_data_by_page(url, **kwargs):\n", " page = 0\n", " params = prepare_params(url, **kwargs)\n", " total_pages = get_total_pages(params)\n", " # We'll use a timestamp to distinguish between versions\n", " timestamp = arrow.now().format(\"YYYYMMDDHHmmss\")\n", " file_path = Path(f\"{slugify(domain)}-cdx-data-{timestamp}.ndjson\")\n", " # Remove any old versions of the data file\n", " try:\n", " file_path.unlink()\n", " except FileNotFoundError:\n", " pass\n", " with tqdm(total=total_pages - page) as pbar1:\n", " with tqdm() as pbar2:\n", " while page < total_pages:\n", " params[\"page\"] = page\n", " results = get_cdx_data(params)\n", " if results:\n", " with file_path.open(\"a\") as f:\n", " writer = ndjson.writer(f, ensure_ascii=False)\n", " for result in convert_lists_to_dicts(results):\n", " writer.writerow(result)\n", " pbar2.update(len(results) - 1)\n", " page += 1\n", " pbar1.update(1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "nbval-skip" ] }, "outputs": [], "source": [ "# Note than harvesting a domain has the same number of pages (ie requests) no matter what filters are applied -- it's just that some pages will be empty.\n", "# So repeating a domain harvest with different filters will mean less data, but the same number of requests.\n", "# What's most efficient? I dunno.\n", "get_cdx_data_by_page(\n", " f\"*.{domain}\",\n", " filter=[\"statuscode:200\", \"mimetype:text/html\"],\n", " collapse=\"urlkey\",\n", " fl=\"urlkey,timestamp,original\",\n", " pageSize=5,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Process the harvested data\n", "\n", "After many hours, and many interruptions, the harvesting process finally finished. I ended up with a 65gb ndjson file. How many captures does it include?" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "tags": [ "nbval-skip" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "213,107,491\n", "CPU times: user 38.5 s, sys: 29.3 s, total: 1min 7s\n", "Wall time: 1min 24s\n" ] } ], "source": [ "%%time\n", "\n", "latest_data = sorted(list(Path(\".\").glob(\"gov-au-cdx-data-*\")), reverse=True)[0]\n", "\n", "count = 0\n", "with latest_data.open() as f:\n", " for line in f:\n", " count += 1\n", "print(f\"{count:,}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Find unique domains" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's get extract a list of unique domains from all of those page captures. In the code below we extract domains from the `urlkey` and add them to a list. After every 100,000 lines, we use `set` to remove duplicates from the list. This is an attempt to find a reasonable balance between speed and memory consumption." ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "tags": [ "nbval-skip" ] }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "da953625af9e49a6a04672c2dac6d62e", "version_major": 2, "version_minor": 0 }, "text/plain": [ "0it [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 10min 47s, sys: 21.6 s, total: 11min 9s\n", "Wall time: 11min 8s\n" ] } ], "source": [ "%%time\n", "# This is slow, but will avoid eating up memory\n", "domains = []\n", "with latest_data.open() as f:\n", " count = 0\n", " with tqdm() as pbar:\n", " for line in f:\n", " capture = json.loads(line)\n", " # Split the urlkey on ) to separate domain from path\n", " domain = capture[\"urlkey\"].split(\")\")[0]\n", " # Remove port numbers\n", " domain = re.sub(r\"\\:\\d+\", \"\", domain)\n", " domains.append(domain)\n", " count += 1\n", " # Remove duplicates after every 100,000 lines to conserve memory\n", " if count > 100000:\n", " domains = list(set(domains))\n", " pbar.update(count)\n", " count = 0\n", "domains = list(set(domains))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "How many unique domains are there?" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "tags": [ "nbval-skip" ] }, "outputs": [ { "data": { "text/plain": [ "28461" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(domains)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "tags": [ "nbval-skip" ] }, "outputs": [ { "data": { "text/html": [ "\n", " | urlkey | \n", "
---|---|
0 | \n", "au,gov,qld,rockhampton | \n", "
1 | \n", "au,gov,ag,sat | \n", "
2 | \n", "au,gov,vic,ffm,confluence | \n", "
3 | \n", "au,gov,nsw,dumaresq | \n", "
4 | \n", "au,gov,wa,dpc,scienceandinnovation | \n", "
\n", " | urlkey | \n", "number_of_pages | \n", "
---|---|---|
0 | \n", "au,gov,qld,rockhampton | \n", "10069 | \n", "
1 | \n", "au,gov,ag,sat | \n", "14 | \n", "
2 | \n", "au,gov,vic,ffm,confluence | \n", "5 | \n", "
3 | \n", "au,gov,nsw,dumaresq | \n", "33 | \n", "
4 | \n", "au,gov,wa,dpc,scienceandinnovation | \n", "438 | \n", "
\n", " | urlkey | \n", "number_of_pages | \n", "0 | \n", "1 | \n", "2 | \n", "3 | \n", "4 | \n", "5 | \n", "6 | \n", "7 | \n", "8 | \n", "9 | \n", "domain | \n", "
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | \n", "au,gov,qld,rockhampton | \n", "10069 | \n", "au | \n", "gov | \n", "qld | \n", "rockhampton | \n", "None | \n", "None | \n", "None | \n", "None | \n", "None | \n", "None | \n", "rockhampton.qld.gov.au | \n", "
1 | \n", "au,gov,ag,sat | \n", "14 | \n", "au | \n", "gov | \n", "ag | \n", "sat | \n", "None | \n", "None | \n", "None | \n", "None | \n", "None | \n", "None | \n", "sat.ag.gov.au | \n", "
2 | \n", "au,gov,vic,ffm,confluence | \n", "5 | \n", "au | \n", "gov | \n", "vic | \n", "ffm | \n", "confluence | \n", "None | \n", "None | \n", "None | \n", "None | \n", "None | \n", "confluence.ffm.vic.gov.au | \n", "
3 | \n", "au,gov,nsw,dumaresq | \n", "33 | \n", "au | \n", "gov | \n", "nsw | \n", "dumaresq | \n", "None | \n", "None | \n", "None | \n", "None | \n", "None | \n", "None | \n", "dumaresq.nsw.gov.au | \n", "
4 | \n", "au,gov,wa,dpc,scienceandinnovation | \n", "438 | \n", "au | \n", "gov | \n", "wa | \n", "dpc | \n", "scienceandinnovation | \n", "None | \n", "None | \n", "None | \n", "None | \n", "None | \n", "scienceandinnovation.dpc.wa.gov.au | \n", "
\n", " | domain | \n", "number_of_pages | \n", "
---|---|---|
6469 | \n", "trove.nla.gov.au | \n", "14,053,042 | \n", "
20708 | \n", "nla.gov.au | \n", "8,852,946 | \n", "
7925 | \n", "collectionsearch.nma.gov.au | \n", "2,548,712 | \n", "
20468 | \n", "passwordreset.parliament.qld.gov.au | \n", "2,089,256 | \n", "
18518 | \n", "parlinfo.aph.gov.au | \n", "2,060,004 | \n", "
2400 | \n", "aph.gov.au | \n", "1,776,889 | \n", "
28205 | \n", "bmcc.nsw.gov.au | \n", "1,419,442 | \n", "
10710 | \n", "jobsearch.gov.au | \n", "1,294,115 | \n", "
27173 | \n", "arpansa.gov.au | \n", "1,279,296 | \n", "
27953 | \n", "abs.gov.au | \n", "992,726 | \n", "
22648 | \n", "catalogue.nla.gov.au | \n", "987,993 | \n", "
7521 | \n", "libero.gtcc.nsw.gov.au | \n", "959,539 | \n", "
28006 | \n", "canterbury.nsw.gov.au | \n", "957,261 | \n", "
13050 | \n", "library.campbelltown.nsw.gov.au | \n", "935,191 | \n", "
3709 | \n", "defencejobs.gov.au | \n", "895,158 | \n", "
11973 | \n", "health.gov.au | \n", "882,471 | \n", "
15637 | \n", "webopac.gosford.nsw.gov.au | \n", "854,803 | \n", "
1550 | \n", "library.lachlan.nsw.gov.au | \n", "838,972 | \n", "
24291 | \n", "accc.gov.au | \n", "828,948 | \n", "
17620 | \n", "data.aad.gov.au | \n", "820,263 | \n", "
{label.upper()}
NSW
VIC
QLD
SA
WA
TAS
NT
ACT
ACT