File size: 24,514 Bytes
65c2aae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# First Steps\n",
    "\n",
    "On the terminal:\n",
    "\n",
    "1. Start zoom call\n",
    "1. Download the code from Ilias to your machine.\n",
    "1. Activate the UniBe VPN.\n",
    "1. Download this notebook and its requirement file to the Ubelix server. From the terminal of your laptop: `scp -r <repo_folder> <your_username>@submit<ID>.unibe.ch:/storage/homefs/<your_username>/`\n",
    "1. Connect to Ubelix (https://ondemand.hpc.unibe.ch/pun/sys/dashboard/batch_connect/sys/codeserver/session_contexts/new)\n",
    "1. Click on \"(VS)Code Server\" and select:\n",
    "    - Code Server version: 4.93.1\n",
    "    - Account: teaching\n",
    "    - wckey: leave it empty\n",
    "    - QoS: job_teaching\n",
    "    - Tick \"I need a GPU\"\n",
    "    - GPU Type: RTX 4090\n",
    "    - Instance Size: small\n",
    "    - Time limit in hours: 2\n",
    "    - Reservation: `CAS_NLP_M6_28_01`\n",
    "    - Jupyter Mode: Jupyter Lab\n",
    "    - Session Configuration: Standard\n",
    "1. Click `Launch`\n",
    "1. Wait for the session to start, then click `Connect to VS Code`\n",
    "1. SSH into a Ubelix node: `ssh <your_username>@submit<ID>.unibe.ch` (`ID` goes from `01` to `04`)\n",
    "1. Load the pre-installed anaconda: `module load Anaconda3/2024.02-1`\n",
    "1. Activate the base environment: `eval \"$(conda shell.bash hook)\"`\n",
    "1. Create a new virtual environment: `conda create -n \"myenv_m6_ws\" python=3.12.11`\n",
    "1. Activate the new virtual environment: `conda activate myenv_m6_ws`\n",
    "1. Install dependencies: `pip install -r requirements/requirements.m6_web_scraping.txt`\n",
    "1. Create a Python kernel for Jupyter: `python -m ipykernel install --user --name myenv_m6_ws`\n",
    "1. In VS Code: `Select Kernel -> Jupyter Kernel` and select the `myenv_m6_ws` kernel (refresh the page if you don't see it)\n",
    "1. Create the folder `data/topic_modelling/` to store the data that will be scraped in this notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "K-3fcEjtlZ0b"
   },
   "source": [
    "# Web Scraping with [Beautiful Soup](https://beautiful-soup-4.readthedocs.io/en/latest/)\n",
    "\n",
    "### Why scraping matters\n",
    "Automates data collection from websites for research, analysis, or building datasets where no official API exists.\n",
    "\n",
    "### Good practices / respect website rules \n",
    "Always check the site's `robots.txt` (text file which tells web crawlers which URLs they may or may not request), terms of service, and avoid overloading servers (use delays, rate limits).\n",
    "Some sites prohibit scraping; only collect publicly available data you’re allowed to use.\n",
    "\n",
    "Example of [robots.txt](https://millercenter.org/robots.txt):\n",
    "- Blocks crawlers from admin pages, user auth/registration, search, node creation, comment reply flows, and some config/readme files (see `Disallaw`).\n",
    "- It explicitly allows crawling CSS, JS, and Images withing ceraing directories which are disallawed (see `# CSS, JS, Images`).\n",
    "\n",
    "For example, they say that crawlers are not allowed to scraped any data within `/core/` directory (i.e., `Disallow: /core/` – [link](https://millercenter.org/core/assets/vendor/jquery/jquery.min.map)), but they allow to scrape CSS, JS, Images within `/core/` (i.e., `Allow: /core/*.js$` – [link](https://millercenter.org/core/assets/vendor/jquery/jquery.min.js?v=4.0.0-rc.1))\n",
    "\n",
    "Additionally, the `robots.txt` does not say anything specific about allowing/disallowing scraping of the speeches section. So, for a well-behaved crawler that follows `robots.txt`, speech pages such as [https://millercenter.org/the-presidency/presidential-speeches/january-20-2025-inaugural-address](https://millercenter.org/the-presidency/presidential-speeches/january-20-2025-inaugural-address) are not blocked by `robots.txt`.\n",
    "\n",
    "Important: `robots.txt` is about crawler access rules; it doesn't override their Terms of Service or copyright — so it's still good practice to check site terms and use rate limits/delays."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "The Miller Center [website](https://millercenter.org/) publishes presidential speeches, oral histories, research, expert analysis, and multimedia resources for scholars, students, and the public. In this tutorial:\n",
    "\n",
    "1. We get familiar with scraping with beautiful soup. We will scrape the data from [Data Source](https://millercenter.org/the-presidency/presidential-speeches). The aim is to make a corpus of speeches of US presidents from the website.\n",
    "2. We become familiar with the structure of the website and inspecting elements visually in a browser.\n",
    "3. We try to get the text for a single URL.\n",
    "4. For each president, we try to get a list of URLs that contain their speeches.\n",
    "5. For each URL, we scrape it and format the speech with some metadata such as the date of speech.\n",
    "6. We save the corpus on Ilias folder and it is meant to be used in Topic Modelling.\n",
    "\n",
    "Note that extracted content often needs cleaning (removing HTML tags, normalizing text) and organizing (CSV, JSON, database)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Task: manual inspection (15 minutes)\n",
    "\n",
    "For any president in say [Washington](https://millercenter.org/president/washington), navigate down to any speech, say [first inaugaural address](https://millercenter.org/the-presidency/presidential-speeches/april-30-1789-first-inaugural-address). There go to  [View all George Washington speeches](https://millercenter.org/the-presidency/presidential-speeches?field_president_target_id[44]=44). Note that the URL has the following structure `https://millercenter.org/the-presidency/presidential-speeches?field_president_target_id[44]=44`. Here the number 44 correspons to George Washington and serves as sort of an ID. If you change the number to say 43, you end up with [Barack Obama](https://millercenter.org/the-presidency/presidential-speeches?field_president_target_id[43]=43). \n",
    "\n",
    "For a speech, say the [thanksgiving-proclamation](https://millercenter.org/the-presidency/presidential-speeches/october-3-1789-thanksgiving-proclamation) speech, open the browser inspect tools and inspect the items, for example the title *October 3, 1789: Thanksgiving Proclamation*:\n",
    "\n",
    "```HTML\n",
    "<h2 class=\"presidential-speeches--title\"><span>October 3, 1789: Thanksgiving Proclamation</span>\n",
    "</h2>\n",
    "```\n",
    "\n",
    "This HTML code creates a second-level heading (`<h2>`) with the title \"October 3, 1789: Thanksgiving Proclamation\". It has a class (`presidential-speeches--title`) for styling, and the text is wrapped in a `<span>` element, which is typically used for applying specific styles or functionality to part of the text (although in this example no styles are applied).\n",
    "\n",
    "Explore other parts of the web pages, and refer the [www.w3schools.com/tags](https://www.w3schools.com/tags/) for tags explanation and examples."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scraping with BeautifulSoup\n",
    "\n",
    "In this exercise, we will use BeautifulSoup to scrape parts of the website in a systematically way. More specifically, we are going to pull a specific speech page via `requests` and  parse it with BeautifulSoup by extracting different sections (transcript, intro, title, date, president)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "XMZZQlTgm0Lf"
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "import pandas as pd\n",
    "from bs4 import BeautifulSoup as bs\n",
    "import tqdm\n",
    "import time\n",
    "import re\n",
    "from pprint import pprint"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**For a single URL**, let us try to **capture the entire response and then try to pick** relevant elements such as **title, name of the president, date, introductory text, and transcript of the speech**.\n",
    "After gathering these pieces of information, we make a small function which when fed an URL, provides an Dataframe object of a certain structure.\n",
    "We will use this to automate the data gathering.\n",
    "\n",
    "Let's try it on Donald Trump's inaugural address, which took place on January 20, 2025.\n",
    "\n",
    "Before running the code, open the [link](https://millercenter.org/the-presidency/presidential-speeches/january-20-2025-inaugural-address) in your browser and use the developer tool to locate the elements containing the:\n",
    "- speech title\n",
    "- transcript\n",
    "- president's name\n",
    "- date\n",
    "- introductory text\n",
    "\n",
    "Identifying those HTML elements now will make it easier to target them when scraping.\n",
    "\n",
    "Hint: the president's name, the date, and the intro appear in the \"About this speech\" panel on the right."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "vn6GKiVonn8b",
    "outputId": "b52dbe15-0c93-48c1-c5ff-f207dc5dddaa"
   },
   "outputs": [],
   "source": [
    "URL = \"https://millercenter.org/the-presidency/presidential-speeches/january-20-2025-inaugural-address\"\n",
    "page = requests.get(URL) # performs an HTTP GET request and returns a requests.Response object (contains status_code, content, etc.)\n",
    "soup = bs(page.content, \"html.parser\") # parses the HTML content using BeautifulSoup. It returns a BeautifulSoup object which provides several functions to navigate and search in the content\n",
    "soup"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pretty print"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(soup.prettify())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the code below, we want to **get the transcript in text format** of the speech. More specifically, we want to extract from the `soup` variable whatever is inside `<div class=\"transcript-inner\">...</div>`.\n",
    "\n",
    "In HTML, the `<div>` element is used to logically group sections of a web page. The `class` attribute acts as a label or name for a `<div>`, allowing you to easily select, style, or find that specific `<div>` among many others on the page.\n",
    "\n",
    "To do so, we are going to use:\n",
    "\n",
    "- `find()`: Finds the first `<div>` element whose class attribute includes `\"transcript-inner\"`. Returns a `bs4.element.Tag` or `None` if not found.\n",
    "- `.text`: Returns the text of that Tag\n",
    "\n",
    "Note that if `find()` returns `None`, `.text` raises AttributeError"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 109
    },
    "id": "B-bdXBTmAJYs",
    "outputId": "d98adff7-60b5-4b04-fed2-fea73c9735b9"
   },
   "outputs": [],
   "source": [
    "soup.find(\"div\", {\"class\":\"transcript-inner\"}).text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's save the speech text in a variable"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "kGeSb0Hr_WVX"
   },
   "outputs": [],
   "source": [
    "speech = soup.find(\"div\", {\"class\":\"transcript-inner\"}).text\n",
    "pprint(speech)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the code below, we want to **extract the introductory text** about this speech (text inside `About this speech` in the right panel). You find it inside `<div class=\"about-sidebar--intro\"><p>...</p>`.\n",
    "Note that `find` returns all the text inside that `<div>`, including text inside its child tags like `<p>` (paragraph)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 72
    },
    "id": "QE16DaQ4L6Bd",
    "outputId": "3f443a6e-2a81-40cb-9d04-7ecfc5086111"
   },
   "outputs": [],
   "source": [
    "soup.find(\"div\", {\"class\":\"about-sidebar--intro\"}).text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the code below, I want to **extract the title** of the page (`January 20, 2025: Inaugural Address`). `<h2>` is a heading tag (level 2), used for section titles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 36
    },
    "id": "7n1CDqhcMHCd",
    "outputId": "f1fd028f-be74-4faf-b789-95f4257e434a"
   },
   "outputs": [],
   "source": [
    "soup.find(\"h2\", {\"class\":\"presidential-speeches--title\"}).text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we **extract the episode date**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 36
    },
    "id": "p06EDYTcMHFh",
    "outputId": "daea2dc2-2742-45a1-f108-48f4fce5a012"
   },
   "outputs": [],
   "source": [
    "soup.find(\"p\", {\"class\":\"episode-date\"}).text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we **extract the president name**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 36
    },
    "id": "ehgr8JWeMHIO",
    "outputId": "7dd50847-c380-47b7-deb3-0a25c87477c0"
   },
   "outputs": [],
   "source": [
    "soup.find(\"p\", {\"class\":\"president-name\"}).text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We encapsulate everything we have seen so far in a function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "pmRAAjkcqou3"
   },
   "outputs": [],
   "source": [
    "def scrape_one_article(URL):\n",
    "  \"\"\"\n",
    "  Function that accepts one URL and returns a dictionary of scraped items such as president, title, date of speech, introduction, speech text\n",
    "  \"\"\"\n",
    "  page = requests.get(URL)\n",
    "  soup = bs(page.content, \"html.parser\")\n",
    "  president = soup.find(\"p\", {\"class\":\"president-name\"}).text or \"Unknown\"\n",
    "\n",
    "  if soup.find(\"div\", {\"class\":\"transcript-inner\"}) is not None:\n",
    "    speech_text = soup.find(\"div\", {\"class\":\"transcript-inner\"}).text or \"Unknown\"\n",
    "  else:\n",
    "    speech_text = \"Unvailable\"\n",
    "\n",
    "  speech_text = re.sub(\"Transcript\",\"\", speech_text)\n",
    "  title = soup.find(\"h2\", {\"class\":\"presidential-speeches--title\"}).text or \"Unknown\"\n",
    "  date = soup.find(\"p\", {\"class\":\"episode-date\"}).text or \"Unknown\"\n",
    "\n",
    "  if soup.find(\"div\", {\"class\":\"about-sidebar--intro\"}) is not None:\n",
    "    intro = soup.find(\"div\", {\"class\":\"about-sidebar--intro\"}).text or \"Unknown\"\n",
    "  else:\n",
    "    intro = \"Unvailable\"\n",
    "  \n",
    "  data_dict = {\n",
    "    \"URL\": URL,\n",
    "    \"president\": president,\n",
    "    \"title\": title,\n",
    "    \"date\": date,\n",
    "    \"intro\": intro,\n",
    "    \"speech_text\": speech_text\n",
    "  }\n",
    "  return data_dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Store the output of `scrape_one_article` in a pandas dataframe."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 81
    },
    "id": "m8AuPmsnrkay",
    "outputId": "77fed8ab-07fb-41a3-a955-cc402e674944"
   },
   "outputs": [],
   "source": [
    "pd.DataFrame([scrape_one_article(URL)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scraping all speeches of a president\n",
    "\n",
    "The next task is to **extract all speeches of Donald Trump** with their links and store them in a pandas DataFrame. \n",
    "\n",
    "Trump ID is 8396: [Donald Trump](https://millercenter.org/the-presidency/presidential-speeches?field_president_target_id[8396]=8396)\n",
    "\n",
    "Before proceeding with the code, **manually inspect the web page** of [Donald Trump](https://millercenter.org/the-presidency/presidential-speeches?field_president_target_id[8396]=8396), **see where are the speeches, and analyse their structure**. This will help you to understand what to scrape. Note that all speeches are at the bottom of the page."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we are going to **extract every `<a>` tag** in the HTML of [Donald Trump](https://millercenter.org/the-presidency/presidential-speeches?field_president_target_id[8396]=8396) **that has an `href` attribute**. This basically will extract all hyperlinks that are present in the HTML response. \n",
    "\n",
    "However, when manually parsing this output, you can see that there are **many unrelevant outputs**, but we can observe that **links of the speeches contain `presidential-speeches`** in the `href` attribute."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "KrZHVV63slle",
    "outputId": "590d60e8-e10b-4117-8324-3e7ab5788eb2"
   },
   "outputs": [],
   "source": [
    "URL = \"https://millercenter.org/the-presidency/presidential-speeches?field_president_target_id[8396]=8396\"\n",
    "page = requests.get(URL)\n",
    "all_soup = bs(page.content, \"html.parser\")\n",
    "link_list = all_soup.find_all('a', href=True) # <a> tag in HTML defines a hyperlink, and the href attribute specifies the URL of the page the link goes to\n",
    "for link in link_list:\n",
    "  print(link)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the code below we **filter the list of all links** (`link_list`) by keeping only those whose HTML contains `\"presidential-speeches/\"`.\n",
    "\n",
    "It appends the `href` attribute (the URL) of each matching link to the `temp_links` list.\n",
    "\n",
    "This way, `temp_links` will contain only URLs that likely point to individual presidential speech pages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "vqBftlDDNgH1",
    "outputId": "5a9d8701-8dc8-4cd8-a6bf-6b8aa208b9da"
   },
   "outputs": [],
   "source": [
    "temp_links = []\n",
    "for link in link_list:\n",
    "  if re.search(\"presidential-speeches/\",str(link)) is not None:\n",
    "     temp_links.append(link['href'])\n",
    "temp_links"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's print the links"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "_4Nvd-NjMeR_",
    "outputId": "75bae8d4-e36c-4e5c-f201-6c4a4b58cfc4"
   },
   "outputs": [],
   "source": [
    "# temp_links = temp_links[2:]\n",
    "temp_links = set(temp_links)\n",
    "temp_links"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that **the list of links might include** irrelevant links that we must filter out, for example because they are links to **speeches of other presidents or non speeches**. In this case, we manually remove them."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For each link in `temp_links`, I want to **scrape the data using the `scrape_one_article`** function defined above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "Jf58qIYRytP0",
    "outputId": "75f765fb-699a-4291-ec75-fc9eb1d738e6"
   },
   "outputs": [],
   "source": [
    "speech_list = []\n",
    "for link in tqdm.tqdm(temp_links):\n",
    "  print(link)\n",
    "  time.sleep(1)\n",
    "  data = scrape_one_article(link)\n",
    "  print(data)\n",
    "  speech_list.append(data)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We print the speech list and we can see that in `president` column there are other presidents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 585
    },
    "id": "vCD9H3aCzqVZ",
    "outputId": "717fe017-8688-49c0-ee1e-e9b1ae0f70b0"
   },
   "outputs": [],
   "source": [
    "pd.DataFrame(speech_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We save the data by only keeping the speeches of Donald Trump."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "speech_list_df = pd.DataFrame(speech_list)\n",
    "trump_df = speech_list_df[speech_list_df[\"president\"].str.contains(\"Donald Trump\", case=False, na=False)].copy()\n",
    "trump_df.to_csv(\"data/topic_modelling/donald_trump_speeches.csv\", index=False)\n",
    "trump_df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9L6ShLiw2AJv"
   },
   "source": [
    "# TODO\n",
    "\n",
    "1. Generate `id2name` map in order to store the mapping between the president IDs and their names. Hint: one possible starting point is [presidential-speeches](https://millercenter.org/the-presidency/presidential-speeches)\n",
    "\n",
    "1. Improve `scrape_one_article` function to extract `speech_text` and `intro` instead of falling back to `Unvailable` when either `soup.find(\"div\", {\"class\":\"transcript-inner\"})` or `soup.find(\"div\", {\"class\":\"about-sidebar--intro\"})` are `None`. Afterwards, collect speeches of one or two presidents and save it in a csv file. Note that some early presidents may have different structure of the webpages in which case, and you may need to further adapt the script to work with the president.\n",
    "    - Upload to Ilias under folder **Module 6 -> Frontier and applications -> Lecture notes -> Paolo's module -> Scraped Data**\n",
    "\n",
    "1. Compute semantic similarity between Donald Trump’s inaugural speech and every other president’s inaugural speech. Requirements:\n",
    "    - Build a dataset containing one inaugural speech per president (URL + president name + speech text). If a president has multiple inaugural addresses, choose a consistent rule (e.g., first term only) and document it.\n",
    "    - Use any similarity method you want (e.g., cosine similarity on TF‑IDF vectors, or cosine similarity between sentence/document embeddings).\n",
    "    - Important note about long speeches (truncation): Many transformer embedding models (e.g., all-MiniLM-L6-v2) only encode up to a limited number of tokens; longer speeches may be truncated, meaning you’re not comparing the full documents. First run a baseline without any special handling so you can see what you get. Then, summarize each inaugural speech with an LLM using the same prompt and target length for all presidents, then embed/compare the summaries instead of the full text.\n",
    "    - Document your findings."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "myenv_m6_ws",
   "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.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}