I'm focused on grasping the essence of the assignment: constructing a Python script for Wikipedia data scraping and visualization. Initially, I'll need to define the exact data to extract and the desired visualization method, establishing clear boundaries. Currently, my thought process is zeroing in on defining a focused scraping target on Wikipedia.
Outlining the Execution Plan
I've sketched out the procedural steps needed: Imports, fetching the URL, parsing the HTML with BeautifulSoup to isolate the target table. Following that, I'll extract relevant data points - the country names and populations. Data cleaning will be essential, including converting population strings into usable integers.
Defining the Data Structures
I'm now contemplating how to optimize the data handling. Utilizing Pandas' read_html seems prudent, especially for the table parsing. The columns will likely need renaming for clarity, and population columns will be converted to numeric types. Also, I'm considering using a dictionary to map countries to population data, to improve the visualization's flexibility and potential for future expansion.
Refining the Approach
I'm now revisiting the overall strategy. Using pandas.read_html is confirmed as the most efficient way to get the data, but I'll need to handle potential parsing errors gracefully. I'll include user-agent headers to avoid being blocked. Next, I'll flesh out data cleaning and visualization function, emphasizing code readability and error handling.
Planning the Implementation
Now, I'm fully immersed in the coding phase, creating the Python script. I've decided to employ pandas.read_html for streamlined data extraction, and focused on implementing proper headers using requests, also ensuring robust error handling. The next step is data cleaning and creating the visualization function using seaborn and matplotlib.
Synthesizing the Solution
I've formulated the complete implementation plan and am currently integrating the scraping and visualization elements. I've switched to utilizing requests with user-agent headers and passing the HTML to pandas.read_html. I've also focused on data cleaning and visualization function, emphasizing code readability and error handling, making sure to dynamically handle column names. I'm now adding comments and error checks.
This creates a complete project. We will scrape the "List of countries and dependencies by population" page on Wikipedia, clean the data, and generate a bar chart of the top 10 most populous countries.
We will use Pandas (for efficient table scraping and data manipulation) and Seaborn/Matplotlib (for visualization).
Prerequisites
You will need to install the following libraries via your terminal:
(Note: lxml is a parser required by Pandas to read HTML).
The Python Script
Save this code in a file named wiki_scraper.py.
python
How it works:
Requests & Headers: We use the requests library to get the HTML. Crucially, we pass a User-Agent header. Wikipedia often blocks scripts that identify themselves simply as "Python-urllib".
Pandas read_html: Instead of manually parsing HTML tags with BeautifulSoup (which can be tedious), we use pd.read_html. This function scans the HTML for <table> tags and automatically converts them into a list of Pandas DataFrames.
Dynamic Column Selection: Wikipedia editors change table headers frequently (e.g., changing "Country" to "Location"). The script searches for column names containing keywords to ensure it doesn't crash if the header creates a minor change.
Data Cleaning (Regex):
Raw population numbers often come as strings like "1,400,000,000". We strip the commas.
Raw country names often contain citations like "China[b]". We use Regex (\[.*\]) to remove the brackets and everything inside them.
We filter out the "World" row, which is usually the first row in the table.
Visualization: We use Seaborn to create a horizontal bar chart. Since populations are large numbers, we add text labels to the end of the bars for readability.
To Run It:
Simply execute the script from your terminal:
bash
python wiki_scraper.py
A window will pop up displaying the bar chart of the top 10 most populous countries.
import requests
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
def scrape_wikipedia_population():
"""
Scrapes the Wikipedia page for countries by population.
Returns a cleaned Pandas DataFrame.
"""
url = "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population"
# Wikipedia requires a User-Agent to prevent 403 Forbidden errors
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
try:
print("Fetching data from Wikipedia...")
response = requests.get(url, headers=headers)
response.raise_for_status() # Check for connection errors
# Pandas can read HTML tables directly.
# This returns a list of all tables found on the page.
# The main population table is usually the first wikitable.
tables = pd.read_html(response.text)
# Locate the correct table. Usually, it's the first one, but we ensure
# it's the right one by looking for specific columns.
df = tables[0]
return df
except Exception as e:
print(f"An error occurred: {e}")
return None
def clean_data(df):
"""
Cleans the raw DataFrame to ensure numeric data and correct column names.
"""
print("Cleaning data...")
# 1. Copy the dataframe to avoid SettingWithCopy warnings
df = df.copy()
# 2. Identify columns. Wikipedia columns change occasionally, so we look for keywords.
# We need the column with country names and the column with population figures.
country_col = [c for c in df.columns if "Location" in c or "Country" in c][0]
pop_col = [c for c in df.columns if "Population" in c][0]
# 3. Rename columns for easier access
df = df.rename(columns={country_col: 'Country', pop_col: 'Population'})
# 4. Keep only necessary columns
df = df[['Country', 'Population']]
# 5. Clean 'Population' column
# Convert to string first, remove non-numeric chars (commas), then to int
df['Population'] = df['Population'].astype(str).str.replace(r'[^\d]', '', regex=True)
df['Population'] = pd.to_numeric(df['Population'], errors='coerce')
# 6. Clean 'Country' column
# Remove references like "[b]", "World", etc.
df['Country'] = df['Country'].astype(str).str.replace(r'\[.*\]', '', regex=True)
# 7. Remove the "World" row if it exists (usually the aggregate total)
df = df[df['Country'] != 'World']
# 8. Drop rows with NaN entries
df = df.dropna()
return df
def visualize_data(df):
"""
Creates a bar chart of the top 10 countries.
"""
print("Generating visualization...")
# Sort by population and take top 10
top_10 = df.sort_values(by='Population', ascending=False).head(10)
# Set plot style
sns.set_theme(style="whitegrid")
plt.figure(figsize=(12, 6))
# Create Bar Plot
barplot = sns.barplot(
x='Population',
y='Country',
data=top_10,
palette='viridis',
hue='Country',
legend=False
)
# Format logic
plt.title('Top 10 Most Populous Countries/Dependencies', fontsize=16)
plt.xlabel('Population (Billions)', fontsize=12)
plt.ylabel('Country', fontsize=12)
# Add text labels to the end of the bars
for p in barplot.patches:
width = p.get_width()
plt.text(
width + (width * 0.01), # x-position
p.get_y() + p.get_height() / 2, # y-position
f'{int(width):,}', # Label text (formatted with commas)
ha='left',
va='center',
fontsize=10
)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
# 1. Scrape
raw_df = scrape_wikipedia_population()
if raw_df is not None:
# 2. Clean
clean_df = clean_data(raw_df)
# 3. Visualize
visualize_data(clean_df)
print("Done!")