# Standard library: dates and paths
from datetime import datetime
from pathlib import Path
# Web scraping, Wikipedia and data
import pandas as pd
import requests
import wikipedia as wiki
from bs4 import BeautifulSoup, SoupStrainer
BIG DATA ANALYTICS WITH PYTHON
ENSEA, Abidjan, Côte d’Ivoire · 30 November – 4 December 2026
<span style="background: #F2A65A; color: #14213D; font-weight: 700; font-size: 13px; padding: 4px 10px; border-radius: 12px;">Module 3 · Data from the Web</span>
<span style="background: #D7E6E4; color: #14213D; font-weight: 600; font-size: 13px; padding: 4px 10px; border-radius: 12px; margin-left: 6px;">⏱ about TODO minutes</span>
Collecting Text Data from the Web
| Objective | Collect text from the web: scrape articles from a news website and download Wikipedia pages for African countries. |
| You will | Scrape article text with requests and BeautifulSoup · Search for and download Wikipedia pages · Record the downloaded pages in a metadata CSV |
| Data | data/raw/ISO-country-list.csv (TODO size and source) |
| Core packages | requests · bs4 · wikipedia · pandas |
Scrape article text from a news website with requests and BeautifulSoup, then use the wikipedia package to download Wikipedia pages for African countries.
Requirements: requests, beautifulsoup4, pandas, wikipedia.
Data: ISO-country-list.csv in data/raw/.
0. Setup and Configuration
Working Directory and Input Files
# ============================================================
# BASE WORKING DIRECTORIES
# ============================================================
# The course folder is the closest folder, going upwards, that contains environment.yml
DIR_COURSE = next(
(p for p in [Path.cwd(), *Path.cwd().parents] if (p / "environment.yml").exists()), None
)
if DIR_COURSE is None:
DIR_COURSE = Path.cwd()
print("Running outside the course folder (e.g. Colab): upload the datasets to data/raw/.")
DIR_DATA = DIR_COURSE / "data" / "raw"
# ============================================================
# INPUT FILES
# ============================================================
# Country names, ISO codes and continents
FILE_ISO_COUNTRIES = DIR_DATA / "ISO-country-list.csv"
# ============================================================
# OUTPUT FOLDERS
# ============================================================
# Downloaded Wikipedia pages and their metadata.csv
DIR_WIKI_DOWNLOADS = DIR_COURSE / "data" / "wiki-downloads"Global Variables for Processing
# ============================================================
# SETTINGS
# ============================================================
# None defined yet.base_url = 'https://www.nyasatimes.com'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
response = requests.get('https://www.nyasatimes.com/rights-activists-press-on-chakwera-to-resign-over-chizuma-saga/', headers=headers)
soup = BeautifulSoup(response.content, 'lxml')mydivs = soup.find_all("div", {"class": "nyasa-content"})len(mydivs)1
texts = [for link in soup.find_all('a', href=True):
url = link['href']
title = link.text
title_len = len(title)
if title_len > 20:
try:
response = requests.get(url, headers=headers)
this_soup = BeautifulSoup(response.content, 'html.parser')
output_dir = DIR_WIKI_DOWNLOADS
metadata_csv = output_dir.joinpath("metadata.csv")
country_list = FILE_ISO_COUNTRIES
cols = ['title', 'original_title', 'url', 'num_categories',
'date_accessed', 'search_term', 'filename']def download_wiki_pages(search_terms_list,
max_files_per_co=100, results_per_search=10000):
data = []
for co_name in search_terms_list:
try:
files_saved = 0
search_results = wiki.search(co_name, results=results_per_search)
for result in search_results:
try:
pg = wiki.page(result)
title = pg.title
date = datetime.now().date()
num_categories = len(pg.categories)
# Write page to file
fname = title.replace(" ", "_")
outf = output_dir.joinpath("{}.txt".format(fname))
pg_content = pg.content
with open(outf, "w") as text_file:
text_file.write(pg_content)
item = {'title': title, 'original_title': pg.original_title,
'num_categories': num_categories, 'date_accessed': date,
'search_term': search_term, 'filename': outf}
data.append(item)
files_saved += 1
print(files_saved, co_name)
if files_saved > max_files_per_co:
break
except:
pass
if files_saved > max_files_per_co:
break
except:
pass
return datadef get_africa_country_list(ISO_file):
df_co = pd.read_csv(country_list)
africa_co = list(df_co.query('Continent == "Africa"')['Country'].values)
return africa_codf_co = pd.read_csv(country_list)
co_list = get_africa_country_list(ISO_file=country_list)results = download_wiki_pages(search_terms_list=co_list[5:],
max_files_per_co=10,
results_per_search=50)
df = pd.DataFrame(results)
df.to_csv(metadata_csv, index=False)Summary
- TODO
- TODO
- TODO
Next: Hello Spark