Clarifying scraping task
The user wants a Python script to scrape and visualize Wikipedia data, but they haven't specified which data or articles. I need to consider asking them clarifying questions or proposing a sample application since they didn't ask for any follow-up. I'll likely use the requests and BeautifulSoup libraries or the Wikipedia API. However, scraping must adhere to Wikipedia's terms. I should also recommend using the API but remember that they asked for scraping, likely for educational purposes. I'll include visualization using libraries like matplotlib or seaborn.Designing a scraping example
Since the user didn't specify details, I should create a specific example, like scraping the table of countries by population from Wikipedia and visualizing the top 10 in a bar chart. Alternatively, I could consider using historical stock data or the "List of countries by GDP." However, the population list seems more practical. I’ll scrape the "List of countries by population (United Nations)," parse the key columns, and create a bar chart of the top 20 populations. I'll organize the code into functions, include error handling, and ensure it adheres to Wikipedia's guidelines. I'll mention dependencies such as requests, BeautifulSoup, pandas, and matplotlib.Creating the scraping script
I’ll create a self-contained script, let’s say script.py, and include a main guard. We’ll start with setting up the requirements using pip and provide a clear code explanation with annotations, ensuring it’s not too detailed but enough to run effectively. While the user didn’t specify what they want to visualize, I can assume they’re looking for a concrete example. I need to be cautious with the distinction between scraping and using an API, but scraping is allowed here. My approach involves importing necessary libraries, defining the URL, and noting that table structures may change.Choosing a parsing method
I think it’s better to use pandas.read_html on the URL, which simplifies things. However, since the user specified "scrape," I should consider showing a manual parse as well. Maybe I can demonstrate both methods, but to keep it focused, I’ll choose the requests plus BeautifulSoup method. It’s good to show how to find the 'table' with the class 'wikitable sortable' and parse each 'tr' instead. I'll outline the function to fetch the country population table, setting headers and raising exceptions if things go wrong. I'll ensure to extract the relevant columns like "Country" and "Population," but be cautious since headers may vary.Developing the final script
Without internet access, I can't check the current markup, but I can approximate. Since the user's request is vague, I can create a concrete example that demonstrates scraping a Wikipedia table. I’ll use pandas.read_html for simplicity and focus on selected columns—specifically "Country" and "Population." I’ll ensure to clean the population data by removing footnote markers and formatting it correctly.
Then, I’ll provide a comprehensive script that includes necessary imports, methods for fetching and cleaning data, and visualizing the top countries. I'll also mention how to install the required libraries and provide guidance for customization while ensuring clarity and conciseness in the final explanation. Below is a complete example that:
- Scrapes a table from a Wikipedia page (countries by population).
- Cleans the data.
- Visualizes the top N countries by population using a bar chart.
You can adapt the same pattern to other Wikipedia pages and tables.
1. Install dependencies
pip install requests pandas matplotlib lxml
(pandas.read_html needs lxml or html5lib; lxml is usually fastest.)
2. Python script: wikipedia_population_viz.py
#!/usr/bin/env python3
"""
Scrape a Wikipedia table and visualize it.
Example: Top N countries by population from
https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population
"""
import requests
import pandas as pd
import matplotlib.pyplot as plt
WIKI_URL = "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population"
def fetch_first_table(url: str) -> pd.DataFrame:
"""
Download the page HTML and parse the first table into a pandas DataFrame.
"""
headers = {
# Identify yourself politely; change this to something meaningful for your use.
"User-Agent": "Mozilla/5.0 (compatible; WikiScraperExample/1.0; +https://example.com)"
}
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status()
# Parse all HTML tables on the page, take the first one
tables = pd.read_html(response.text)
if not tables:
raise ValueError("No tables found on the Wikipedia page.")
return tables[0]
def clean_population_table(df: pd.DataFrame) -> pd.DataFrame:
"""
From the raw table, keep only the country and population columns
and clean them up for plotting.
"""
# Find the likely country and population columns by name
try:
country_col = next(c for c in df.columns if "Country" in str(c))
pop_col = next(c for c in df.columns if "Population" in str(c))
except StopIteration:
raise ValueError(
f"Could not find 'Country' and 'Population' columns in table. "
f"Columns found: {list(df.columns)}"
)
df = df[[country_col, pop_col]].copy()
# Remove footnote markers like [1], [a], etc.
df[country_col] = (
df[country_col]
.astype(str)
.str.replace(r"\[.*?\]", "", regex=True)
.str.strip()
)
# Clean population numbers:
# - Convert to string
# - Remove footnotes
# - Remove commas
# - Extract digits and convert to int
pop_series = (
df[pop_col]
.astype(str)
.str.replace(r"\[.*?\]", "", regex=True)
.str.replace(",", "", regex=False)
.str.extract(r"(\d+)", expand=False)
)
df["Population"] = pop_series.astype("Int64") # nullable integer
df = df.dropna(subset=["Population"]).astype({"Population": int})
df = df.rename(columns={country_col: "Country"})
return df
def plot_top_countries(df: pd.DataFrame, top_n: int = 20, output_file: str | None = None) -> None:
"""
Plot a bar chart of the top N countries by population.
"""
top = df.sort_values("Population", ascending=False).head(top_n)
plt.figure(figsize=(12, 6))
plt.bar(top["Country"], top["Population"])
plt.xticks(rotation=75, ha="right")
plt.xlabel("Country")
plt.ylabel("Population")
plt.title(f"Top {top_n} countries by population (from Wikipedia)")
plt.tight_layout()
if output_file:
plt.savefig(output_file, dpi=150)
print(f"Saved plot to {output_file}")
else:
plt.show()
def main():
print(f"Fetching table from: {WIKI_URL}")
raw_table = fetch_first_table(WIKI_URL)
cleaned = clean_population_table(raw_table)
print("Sample of cleaned data:")
print(cleaned.head())
# Change top_n if you want more/less countries
plot_top_countries(cleaned, top_n=15)
if __name__ == "__main__":
main()
3. Run the script
From the terminal:
python wikipedia_population_viz.py
- It will fetch the Wikipedia page once.
- Parse the first table it finds.
- Clean it and print a preview.
- Show a bar chart of the top 15 countries by population.
4. Adapting this to other Wikipedia data
To reuse this structure for other pages:
- Change
WIKI_URL to another Wikipedia article with a table you care about.
- Inspect
df.columns after fetch_first_table to see the column names.
- Modify
clean_population_table (or create a new cleaner) to:
- Select the right columns.
- Clean types (e.g., convert to int/float/datetime).
- Create a different plotting function (line plot, scatter, etc.) using
matplotlib or another library.
If you tell me what specific data or article you want to work with, I can adjust the script to fit that exactly.