Here's a Python script that extracts potential names from the Wikipedia article about Donald Trump using web scraping techniques. The script uses BeautifulSoup for HTML parsing and spaCy for named entity recognition to identify potential names:
python
import requests
from bs4 import BeautifulSoup
import spacy
import re
from urllib.parse import urljoin
# Load English language model for spaCy
nlp = spacy.load("en_core_web_sm")
def get_wikipedia_content(url):
"""Fetch content from Wikipedia article"""
try:
response = requests.get(url)
response.raise_for_status()
return response.text
except requests.RequestException as e:
print(f"Error fetching URL: {e}")
return None
def extract_text_from_html(html_content):
"""Extract text content from HTML"""
soup = BeautifulSoup(html_content, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Get main content
content = soup.find('div', class_='mw-parser-output')
if content:
# Get text
text = content.get_text()
# Break into lines and remove leading/trailing space
lines = (line.strip() for line in text.splitlines())
# Break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
# Drop blank lines
text = ' '.join(chunk for chunk in chunks if chunk)
return text
return ""
def extract_names(text):
"""Extract potential names using spaCy"""
# Process text with spaCy
doc = nlp(text)
# Extract person names
names = set()
for ent in doc.ents:
if ent.label_ == "PERSON":
# Clean the name
name = ent.text.strip()
# Basic validation to filter out obvious non-names
if re.match(r'^[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*$', name):
names.add(name)
return sorted(list(names))
def main():
url = "https://en.wikipedia.org/wiki/Donald_Trump"
print(f"Fetching content from: {url}")
# Get HTML content
html_content = get_wikipedia_content(url)
if not html_content:
return
# Extract text
text_content = extract_text_from_html(html_content)
if not text_content:
print("Could not extract content from the page")
return
# Extract names
print("\nExtracting potential names...")
names = extract_names(text_content)
# Print results
print(f"\nFound {len(names)} potential names:")
for i, name in enumerate(names, 1):
print(f"{i}. {name}")
if __name__ == "__main__":
main()
To run this script, you'll need to install the required packages first:
Uses requests to fetch the HTML content of the Wikipedia page
Uses BeautifulSoup to parse the HTML and extract the main content
Uses spaCy for natural language processing to identify named entities
Filters for entities labeled as "PERSON"
Applies basic validation to ensure the extracted names follow common naming patterns
Removes duplicates and sorts the names alphabetically
Important notes:
The script uses spaCy's named entity recognition, which isn't perfect and might:
Miss some names
Include some false positives
Include fictional character names or other proper nouns that resemble names
The script includes basic name validation to filter out obvious non-names, but some invalid entries might still get through.
Wikipedia content can change, so the results might vary over time.
The script respects Wikipedia's structure but might need adjustments if the page structure changes.
For production use, you should:
Add error handling for network issues
Respect Wikipedia's robots.txt
Consider using the Wikipedia API instead of direct scraping
Add rate limiting
Handle potential encoding issues
Sample output might look like:
code
Fetching content from: https://en.wikipedia.org/wiki/Donald_Trump
Extracting potential names...
Found X potential names:
1. Abraham Lincoln
2. Andrew Jackson
3. Barack Obama
...
The actual list of names will be much longer and will include various political figures, family members, and other people mentioned in the article.
To improve the accuracy, you could:
Add more sophisticated name validation
Cross-reference with a database of known names
Add context analysis to filter out non-person names
Use additional NLP techniques to verify names
Remember that web scraping should be done responsibly and in accordance with the website's terms of service and robots.txt file.