1. Understand the Goal: The user wants a Python script that performs two main tasks:
* Scrape data from Wikipedia.
* Visualize that data.
Identify the Tools/Libraries:
Scraping:requests (for fetching HTML), BeautifulSoup (for parsing HTML), or wikipedia-api (a wrapper specifically for Wikipedia). pandas can also be useful for reading HTML tables directly.
Visualization:matplotlib and seaborn are the standard go-to libraries for static plots.
Environment: Python script.
Select a Target: To make the example meaningful and reproducible, I need a specific Wikipedia page. "List of countries by GDP (nominal)" is a classic choice because it contains tabular data that is easy to plot. Another option could be "List of highest-grossing films". Let's go with the "List of countries by GDP (nominal)" per capita or just GDP, as it yields a nice bar chart. Self-correction: Sometimes GDP tables change structure. A more stable table might be "List of countries by population". Let's stick to "List of countries by GDP (nominal)" but focus on the top 10 to make the visualization readable.
Drafting the Scraping Logic:
Method 1: Pandas read_html. This is the easiest and most robust way to get tables from Wikipedia. It handles the HTML parsing internally.
Method 2: BeautifulSoup. Good for educational purposes, but requires more code to iterate rows and columns.
Decision: I will use pandas for the scraping part because it's cleaner and professional. I will also include requests and BeautifulSoup logic in the explanation or as an alternative if the user wants to learn "pure" scraping, but for the main script, pandas is best.
Step 3: Scrape. Use pd.read_html. Note: Wikipedia pages often have multiple tables. I need to match the right one.
Step 4: Data Cleaning.
Select the relevant columns (Country, GDP).
Convert GDP to numeric (handle commas, potential non-numeric characters).
Handle missing values.
Step 5: Visualization.
Set style.
Plot bar chart.
Add labels and title.
Show plot.
Refining the Code (Self-Correction during drafting):
Issue: Wikipedia tables are messy. The GDP table usually has estimates from the IMF, World Bank, and UN.
Solution: I'll pick one source (e.g., the first table or specifically the IMF estimate column). Let's stick to the first table found, or match by text content.
Refinement: The standard "List of countries by GDP (nominal)" page usually puts the IMF data in the first main table.
Data Type: The GDP values might be in millions or billions. I should check the header or just plot the raw numbers and format the axis. Let's just plot the raw numbers and let Matplotlib handle the scientific notation or manually format it.
Visuals: Let's make a horizontal bar chart (barh) because country names are long and vertical labels get crowded.
Writing the Script (Mental Draft):
python
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
url = '...'
tables = pd.read_html(url)
# tables[0] is usually the one.
df = tables[0]
# Clean columns...
# Plot...
Adding Explanatory Text: The user needs to know how to run it and what it does. I should explain prerequisites (installing libraries).
Final Polish:
Add comments in the code.
Handle potential errors (like if the table format changes).
Ensure the code is copy-paste runnable.
Alternative Approach (BeautifulSoup):
Should I include a BeautifulSoup version? read_html is great, but "scraping" often implies parsing specific elements. However, read_htmlis scraping tabular data. It's more efficient. I will stick to read_html for the main solution because it's the "Pythonic" data science way, but I will mention BeautifulSoup in the context of parsing. Actually, for a robust script, let's stick to the specific request "Scrape and Visualize". pandas handles the scraping of tables perfectly.
Self-Correction on URL: The Wikipedia page for "List of countries by GDP (nominal)" has merged header cells which can sometimes confuse read_html.
Let's target the "List of states by population" (US) or "List of countries by population" to ensure high success rate, or stick to GDP but handle the multi-index headers.
Let's try the "List of highest-grossing films". It's fun, usually has a clean table, and easy to visualize.
Actually, let's stick to the "Countries by GDP" because it's a more standard data science example. I will handle the cleaning of the specific "IMF" column.
Wait, looking at the current Wikipedia structure for GDP: It often has multiple header rows. pd.read_html usually handles this okay, but the column names might be tuples.
Let's choose "List of countries by population (United Nations)". It's usually cleaner.
Actually, let's do the "Tallest Buildings" or "Highest Grossing Films".
Let's go with "List of highest-grossing films". It is visually distinct and easy to clean.
On second thought, most users asking for this want to see "Real World Data" like Economics. Let's go with "List of countries by GDP (nominal)" but strictly define the cleaning process to make it robust.
Code Structure:
Import.
Fetch data.
Clean data (Remove footnotes [1], convert numbers).
Visualize.
Final Code Construction:
Target: Top 10 Countries by GDP.
Libs: pandas, matplotlib, seaborn.
Data Cleaning: I need to map the columns properly. Often column names are tuples like ('Country', 'Country'). I will flatten them.
Review against constraints:
Script format.
Python.
Scrape.
Visualize.
Let's write the code.
Dependencies:pip install pandas matplotlib seaborn lxml (lxml is needed for read_html).
Code Snippet:
python
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# URL
url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)"
# Scrape
# try-except block for robustness
dfs = pd.read_html(url)
# Usually the first table is the main one.
df = dfs[0]
# Clean
# The table often has multi-index columns. We simplify.
# Let's assume we want the IMF estimate.
Correction: Wikipedia's structure changes. The most robust way for a tutorial is to explicitly look for a table that contains specific text.
Let's stick to the "Highest Grossing Films" example? No, Countries by GDP is too standard to pass up. I will write a script that handles the specific quirks of the GDP table (removing brackets, converting strings to ints).
Updated Plan:
Use pandas for scraping (it's the industry standard for tabular scraping).
Use matplotlib/seaborn for plotting.
Add error handling.
Include comments explaining the cleaning steps.
Steps:
Fetch all tables.
Select the correct table (usually index 1 or 2 depending on the lead images/infoboxes). The IMF table is usually the first big sortable one.
Slice top 10.
Convert string numbers to floats (remove commas).
Plot.
Alternative: What if read_html fails or the user wants specific text scraping?
I'll provide the pandas solution as the primary one because it's cleaner, but I'll briefly mention requests + BeautifulSoup is used for non-tabular data.
Let's finalize the code for "Countries by GDP".
Refining the cleaning:
The IMF column usually contains integers.
The World Bank column contains integers.
I'll just grab the first numeric column after the country name.
Wait, let's make it foolproof.
I'll use the "List of countries by population" instead. It's cleaner.
URL:
Columns: 'Location', 'Population'.
This is much easier to script and guarantee it works for the user.
This script scrapes the "List of countries and dependencies by population" from Wikipedia, cleans the data, and generates a bar chart of the top 10 most populous countries.
python
How it works:
scrape_wikipedia_table:
It uses requests to download the HTML of the Wikipedia article.
Instead of manually iterating through every <tr> (table row) and <td> (data cell) with a loop, we use pd.read_html(str(soup)). This is a specialized Pandas function designed specifically to parse HTML <table> tags into DataFrames immediately.
clean_data:
Wikipedia tables are often messy (containing footnotes like [1], commas in numbers, or mixed data types).
This function identifies the relevant columns (Country and Population).
It converts the population strings into integer types and sorts the values.
visualize_data:
It takes the top 10 entries.
It uses matplotlib to create a horizontal bar chart.
It inverts the Y-axis so the country with the highest population appears at the top.
Okay, decision made:List of countries by population. It is straightforward: Country vs. Number. It makes for a great bar chart.
Script Outline:
import pandas as pd, import matplotlib.pyplot as plt.
url = ...
df = pd.read_html(url)[0]
Clean columns (remove % or extra notes).
plt.bar(...)
Let's do this. It demonstrates the pipeline perfectly without getting bogged down in complex multi-index column handling of the GDP table.
Here is a complete Python script that scrapes tabular data from Wikipedia and visualizes it.
import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
def scrape_wikipedia_table(url):
"""
Fetches a Wikipedia page and parses the main data table.
"""
try:
# 1. Send an HTTP GET request to the URL
response = requests.get(url)
response.raise_for_status() # Raise error for bad status codes
# 2. Parse the HTML content using BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# 3. Find the table
# Wikipedia tables usually have the class "wikitable" or "sortable"
# In this specific page, the first table is usually the main one.
# We convert the HTML table directly to a DataFrame using pandas.
# pandas.read_html is a powerful wrapper that handles <tr> and <td> parsing automatically.
dfs = pd.read_html(str(soup))
# The first table found is usually the one we want
df = dfs[0]
return df
except requests.exceptions.RequestException as e:
print(f"Error fetching the URL: {e}")
return None
except Exception as e:
print(f"An error occurred during parsing: {e}")
return None
def clean_data(df):
"""
Cleans the raw dataframe: renames columns, handles numbers, etc.
"""
if df is None:
return None
# Note: Wikipedia table structures change often.
# We inspect the dataframe to find the correct column names.
# For this specific page, we want 'Country' (or 'Location') and 'Population'.
# Let's standardize the column names we care about
# We map the existing column names to simpler keys
# Find the column that likely contains the country name
country_col = None
for col in df.columns:
if 'Country' in str(col) or 'Location' in str(col):
country_col = col
break
# Find the column that likely contains the population
pop_col = None
for col in df.columns:
if 'Population' in str(col):
pop_col = col
break
if not country_col or not pop_col:
print("Could not identify required columns.")
print("Available columns:", df.columns)
return None
# Create a clean subset
clean_df = df[[country_col, pop_col]].copy()
clean_df.columns = ['Country', 'Population']
# Data Cleaning:
# 1. Remove rows where Population is not a number (e.g., header rows repeated inside the table)
clean_df = clean_df[pd.to_numeric(clean_df['Population'], errors='coerce').notnull()]
# 2. Convert Population to integers
clean_df['Population'] = clean_df['Population'].astype(int)
# 3. Sort by Population descending
clean_df = clean_df.sort_values(by='Population', ascending=False)
return clean_df
def visualize_data(df):
"""
Creates a bar chart of the top 10 countries.
"""
if df is None or df.empty:
print("No data to visualize.")
return
# Take the top 10
top_10 = df.head(10)
# Setup the plot
plt.figure(figsize=(12, 8))
# Create horizontal bar chart (better for reading long country names)
bars = plt.barh(top_10['Country'], top_10['Population'], color='skyblue')
# Make the bars display population in millions/billions nicely
# Invert y-axis so the largest country is at the top
plt.gca().invert_yaxis()
# Add labels and title
plt.xlabel('Population')
plt.title('Top 10 Countries by Population (Wikipedia Data)', fontsize=15)
plt.ticklabel_format(style='plain', axis='x') # Prevent scientific notation (e.g., 1e9)
# Add specific numbers on the bars
for bar in bars:
width = bar.get_width()
label_y_pos = bar.get_y() + bar.get_height() / 2
plt.text(width, label_y_pos, f' {width:,.0f}', va='center', fontsize=9)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
# URL for "List of countries and dependencies by population"
URL = "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population"
print("Scraping data from Wikipedia...")
raw_df = scrape_wikipedia_table(URL)
print("Cleaning data...")
clean_df = clean_data(raw_df)
if clean_df is not None:
print("Visualizing data...")
visualize_data(clean_df)