We are going to use requests to get the webpage and BeautifulSoup to parse it.
However, note that the user did not specify the news website.
Since we don't have a specific website, we can't write the exact selectors.
But we can write a generic example that might work for a typical news site by looking for common headline tags (like , , etc.) or by class names that are often used for headlines.
However, without knowing the structure of the specific website, we might get a lot of irrelevant tags.
Alternatively, we can let the user specify the website URL and then try to extract text from heading tags.
But note: the user said "all the headlines from a news website's homepage", so we are going to assume we are allowed to use a generic approach.
Let's plan:
Ask the user for a URL (or we can hardcode one for example, but better to make it flexible).
Fetch the page with requests.
Parse with BeautifulSoup.
Find all the headline elements. Common tags: h1, h2, h3, and sometimes by class (like 'headline', 'title', etc.)
Print the text of each headline.
However, note that some sites might have multiple h1, h2, etc. and not all are headlines. Also, some headlines might be in other tags.
Since we don't have a specific site, we can try a combination:
Option 1: Use the semantic tags: we can look for tags and then get the heading within, but not all sites use article for every headline.
Option 2: Use a list of common class names that contain headlines. But this might be too broad.
Since it's a simple scraper, we can do:
soup.find_all(['h1', 'h2', 'h3'])
But this might get too many non-headlines (like navigation, footer, etc.)
Alternatively, we can look for the main content area and then extract headings within that. But again, without knowing the site structure, it's hard.
Given the ambiguity, I will write a script that:
Fetches the page from a given URL.
Extracts text from all h1, h2, h3 tags and prints them.
But note: the user might want to avoid duplicates? And we might get the same headline in multiple tags?
Alternatively, we can use a more sophisticated approach by looking for the main content area. However, without a specific site, I'll stick to the simple one.
Let's write the code accordingly.
However, note: some news sites have dynamic content (JavaScript) and requests won't get the full page. But the user asked for a simple scraper, so we assume static.
Steps:
Import libraries: requests, BeautifulSoup.
Define the URL (we'll take it as input from the user or set a default for example).
Send a GET request and check for success.
Parse the content.
Find all h1, h2, h3 tags and extract the text, then print.
But wait, the user might want to see the headlines in the order they appear? We can use find_all which returns in order.
Let's code accordingly.
However, note: the user might have a specific website in mind and we are just giving a template. So we can also note that the user might need to adjust the selectors.
Let me write a function that takes a URL and prints the headlines.
But also, we might want to avoid printing the same headline multiple times? For example, if an h2 is inside an h1? Actually, that's not valid HTML. But we might get the same text from multiple tags (like the same headline in h1 and then in h2 for a subheading). We'll just print each tag's text.
We can also strip whitespace and skip empty strings.
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
for headline in soup.find_all(['h1', 'h2', 'h3']):
text = headline.get_text().strip()
if text: # skip empty
print(text)
else:
print("Failed to retrieve the webpage")
But note: some sites might have a lot of h1, h2, h3 in the navigation and footer. So this might not be perfect.
Alternatively, we can look for a specific container that holds the main news. But without knowing the site, we can't.
Since the user asked for a simple scraper, we'll leave it at that and note that for production use, one would need to adjust the selectors per site.
However, if we want to be a bit smarter, we can look for the tag or tags and then get the headings within. Let's try:
main_content = soup.find('main') or soup.find('article') or soup.find('div', class_='content') or soup.find('div', class_='main-content') ... but again, without knowing the site.
Since the problem says "a news website's homepage", let's assume the main content is in a tag or a div with a common class.
But to keep it simple and because we don't know the site, I'll stick to the first approach and then let the user adjust.
Alternatively, we can combine: first try to find the main content area (by tag or class) and then extract headings only from that area. But if we don't find the main area, we fall back to the entire document.
However, the user might not know how to adjust. So let's do:
Step 1: Try to find the main content by looking for or or a div with class containing 'content' or 'main' (common patterns).
Step 2: If we find one, then extract headings only from that part. Otherwise, use the whole soup.
This might reduce noise.
Let's implement:
main_tags = soup.find_all(['main', 'article'])
if main_tags:
# We'll take the first one (usually there's one main)
content_soup = main_tags[0]
else:
# Try by class
content_div = soup.find('div', class_=lambda x: x and ('content' in x.lower() or 'main' in x.lower()))
if content_div:
content_soup = content_div
else:
content_soup = soup
Then do: content_soup.find_all(['h1','h2','h3'])
But note: some sites have multiple main content areas? We take the first.
However, this is still heuristic and might fail.
Given the complexity, I think for a simple example we should just use the entire document and let the user know they might need to adjust.
But since the instruction says "simple", I'll go with the entire document.
However, the user might run this on a site that has a lot of headings in the header and footer. So let's at least try to exclude the header and footer.
We can look for the and and remove them from the soup? But note: the soup object is the whole document, we can extract the main content by excluding known tags? Not straightforward.
Alternatively, we can look for the and then remove and from it? But again, not all sites use these tags.
Given the time, I think we should stick to the simple version and then in the comments, note that for better results, one should adjust the selectors.
Let me write the code accordingly.
However, the user might want to use a specific CSS selector? We can make it configurable? But the problem says "using a library like BeautifulSoup", so we are using BeautifulSoup.
Since the problem is open-ended, I'll write a function that takes a URL and an optional list of tags (default to ['h1','h2','h3']) and prints the text.
But also, we might want to return the list so it can be used programmatically? The user said "extract", so let's return a list.
But note: the user might want to use it in a script.
Let's code accordingly.
However, we must handle exceptions (like network errors, etc.)
Revised plan:
import requests
from bs4 import BeautifulSoup
def extract_headlines(url, tags=['h1','h2','h3']):
try:
response = requests.get(url, timeout=10)
response.raise_for_status() # will raise an exception for 4xx/5xx
except requests.RequestException as e:
print(f"Error fetching the page: {e}")
return []
code
soup = BeautifulSoup(response.content, 'html.parser')
headlines = []
for tag in soup.find_all(tags):
text = tag.get_text().strip()
if text:
headlines.append(text)
return headlines
if name == "main":
url = input("Enter the URL of the news website: ").strip()
headlines = extract_headlines(url)
for i, headline in enumerate(headlines, 1):
print(f"{i}. {headline}")
But note: the user might want to specify the tags? We can make the function more flexible by allowing a CSS selector? But the problem says "headlines", and typically they are in heading tags.
However, sometimes headlines are in or with a specific class. So we might want to allow the user to pass a list of CSS selectors? But that's more complex.
Given the simplicity, I'll stick to tags.
But wait: the user said "using a library like BeautifulSoup", so we are using BeautifulSoup. We can also use CSS selectors with soup.select. So maybe we can change the function to accept CSS selectors? But then the default would be the heading tags.
Let me change: instead of tags, we can accept a list of CSS selectors. But then we have to use soup.select for each selector and combine.
However, the problem says "headlines", and in many news sites, the headlines are in:
h1, h2, h3, .headline, .title, .entry-title, etc.
So we can define a list of common selectors for headlines.
But again, without knowing the site, we can't be sure.
Since the user might not know CSS selectors, let's stick to tags for the default and allow the user to pass a list of CSS selectors if they want.
But the function signature would be:
def extract_headlines(url, selectors=None):
if selectors is None:
selectors = ['h1', 'h2', 'h3']
Then for each selector in selectors, we do soup.select(selector) and then get the text.
However, note: soup.select returns a list of elements for each selector. We can combine all.
headlines = []
for selector in selectors:
for element in soup.select(selector):
text = element.get_text().strip()
if text:
headlines.append(text)
But then we might get duplicates if an element matches multiple selectors? We can use a set to avoid duplicates? But the same headline might appear in multiple selectors (like h1 and also .headline). But that's the same element? Actually, if an element has both the tag and the class, then it would be matched by two selectors? Then we would get the same text twice.
We can avoid duplicates by using a set of texts? But then two different elements with the same text would be considered duplicate? That might be okay for headlines? Not necessarily.
Alternatively, we can avoid duplicates by element? We can keep a set of element ids? But not all elements have ids.
Given the complexity, I think we should not worry about duplicates for now and just return all matches.
But note: the same headline might appear in the page multiple times (like in the header and in the article). We might want to avoid that? The user might want all occurrences? The problem says "extract all the headlines", so maybe all.
However, let's stick to the simple version and not worry about duplicates.
So:
Let's change the function to accept selectors (list of CSS selectors) and default to ['h1','h2','h3'].
But note: the user might pass a mix of tags and classes? CSS selectors can be either.
However, the user might not know CSS. So we can also allow the old way (tags) by converting tags to CSS selectors? Actually, a tag name is a valid CSS selector.
So we can just use the list as CSS selectors.
But wait: what if the user wants to use the old tag list? They can pass ['h1','h2','h3'] and it's the same.
However, note: soup.select returns elements in the order they appear in the document for each selector, but if we do multiple selectors, the order will be by selector. So we might get all h1 first, then h2, etc. That might not be the visual order.
We can do:
code
elements = []
for selector in selectors:
elements.extend(soup.select(selector))
Then we have to sort by the order in the document? But we lost the original order because we extended by selector.
Alternatively, we can do:
code
all_elements = set()
for selector in selectors:
for element in soup.select(selector):
all_elements.add(element)
Then we have to sort by the element's position in the tree? We can use element.parent and then find the index? That's complex.
Since the user might want the visual order, we can do:
code
We can get all the elements that match any of the selectors and then sort by their `sourceline`? But BeautifulSoup doesn't store that by default.
Alternatively, we can use the find_all with a list of tags? That returns in document order. But for CSS selectors, we don't have that.
Given the complexity, and since the default is just tags, we can use soup.find_all for tags and for classes we have to use select? Actually, find_all can also take a class_ parameter, but for multiple classes and combinations, select is easier.
But note: the user might pass a mix of tag names and CSS selectors. We can try to convert tag names to a regex? Not straightforward.
Let me stick to the original plan of using find_all for tags and then if the user passes a selector that is not a simple tag (like has a dot or bracket) then we use select? That's too complicated.
Since the problem says "simple", let's just use soup.select for all selectors and then we don't care about the order? Or we can try to get the order by using the soup.select with a combined selector? But then we have to combine the selectors with commas.
We can do:
code
combined_selector = ', '.join(selectors)
elements = soup.select(combined_selector)
This will return all elements that match any of the selectors, in the order they appear in the document.
That's better.
So:
code
combined_selector = ', '.join(selectors)
elements = soup.select(combined_selector)
Then we extract the text from each.
But note: if the same element matches multiple selectors, it will appear only once in the result of select? Yes, because select returns each element once.
So we can do:
code
headlines = []
for element in elements:
text = element.get_text().strip()
if text:
headlines.append(text)
This should be in document order.
Let's change the function accordingly.
However, what if the user passes an empty list? Then we get no headlines. We can set a default.
Let's code accordingly.
But note: the user might pass a single string? We can convert to list if it's a string? Or we can accept both? Let's assume the user passes a list.
We can do:
code
if isinstance(selectors, str):
selectors = [selectors]
But the default is a list, so if they pass a string we convert.
Alternatively, we can always treat it as a list and if it's a string, we put it in a list.
Let's do:
code
if not isinstance(selectors, (list, tuple)):
selectors = [selectors]
Then combine.
But wait: what if the user passes a tuple? We can handle.
Let's code accordingly.
However, note: the user might pass a list of strings, which is what we want.
So:
Steps in function:
code
1. Check and convert selectors to list if it's a string.
2. Combine with commas.
3. Use soup.select(combined_selector)
4. Extract text.
But note: the user might have a very long list of selectors? The combined string might be long, but that's okay.
Let's write the function.
However, note: the user might want to use the same function for a site that requires JavaScript? We are not handling that. We are just using requests.
We'll assume static.
Code:
import requests
from bs4 import BeautifulSoup
def extract_headlines(url, selectors=['h1', 'h2', 'h3']):
if not isinstance(selectors, (list, tuple)):
selectors = [selectors]
code
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.RequestException as e:
print(f"Error fetching the page: {e}")
return []
soup = BeautifulSoup(response.content, 'html.parser')
combined_selector = ', '.join(selectors)
elements = soup.select(combined_selector)
headlines = []
for element in elements:
text = element.get_text().strip()
if text:
headlines.append(text)
return headlines
Then in main, we can do:
code
if __name__ == "__main__":
url = input("Enter the URL: ").strip()
# You can also let the user specify selectors? But for simplicity, we use default.
headlines = extract_headlines(url)
for i, h in enumerate(headlines, 1):
print(f"{i}. {h}")
But note: the user might want to specify selectors from command line? We can use argparse, but the problem says simple.
Let's keep it simple and just use the default.
However, if we want to be more flexible, we can ask the user if they want to use custom selectors? But again, simple.
So we'll just use the default.
But wait: the user might run this on a site that uses different tags for headlines. We can note that in the comments.
Let me write the code accordingly.
However, note: some news sites use for the main headline and then for other headlines, but sometimes they use for minor headlines. We are getting all.
This should be okay.
Let's test with a known news site? But we don't have one in mind.
We can test with a sample HTML? But that's beyond the scope.
We'll just write the code and hope the user adjusts the selectors if needed.
But note: the user might not know how to get the CSS selectors. We can tell them to inspect the page and find the common class or tag for headlines.
We'll print a message if no headlines are found.
Revised main:
code
if __name__ == "__main__":
url = input("Enter the URL of the news website: ").strip()
print("Using default selectors: h1, h2, h3. If you get too many or too few, you may need to adjust the selectors.")
headlines = extract_headlines(url)
if headlines:
print(f"Found {len(headlines)} headlines:")
for i, h in enumerate(headlines, 1):
print(f"{i}. {h}")
else:
print("No headlines found. Try adjusting the selectors.")
We can also let the user input selectors? But again, simple.
Alternatively, we can have a configuration file? No.
Given the simplicity, we'll leave it at that.
But note: the user might want to save to a file? Not required.
Let's write the code accordingly.
However, we must consider that some sites might block requests without a user-agent. We can set a user-agent header to mimic a browser.
But note: we are not handling cookies or sessions. It's a simple get.
Let's code accordingly.
Also, we should handle encoding? requests usually handles that.
We'll use response.content and let BeautifulSoup figure out the encoding, or we can use response.text and let BeautifulSoup use that? But response.content is bytes and BeautifulSoup can handle.
I'll use response.content.
Let's write the code.
However, note: some sites might have relative URLs for resources, but we are not following links, so it's okay.
We are just getting the homepage.
Code:
I'll help you create a simple web scraper to extract headlines from a news website. However, I must include an important disclaimer first:
⚠️ Important Legal & Ethical Note:
Check robots.txt: Always check https://website.com/robots.txt to see if scraping is allowed
Review Terms of Service: Many websites prohibit scraping in their ToS
Be respectful: Add delays between requests, don't overload servers
Check for APIs: Many news sites offer official APIs (often free for limited use)
Copyright: Content may be copyrighted - extracted data should be used appropriately
Simple News Headline Scraper Example
python
How to Customize for a Specific Site
Inspect the website:
Right-click on a headline → "Inspect" (Chrome/Firefox)
Identify:
Which HTML tags are used (h1, h2, etc.)
What CSS classes are applied (class="headline", class="title", etc.)
Structure (are headlines in <a> tags? in specific containers?)
Update the selectors in the scrape_news_headlines() function:
python
# Example for BBC News (hypothetical - you must verify):
# headlines = soup.find_all('h3', class_='gs-c-promo-heading__title')
# Example for CNN (hypothetical):
# headlines = soup.select('div.container__headline span')
Test incrementally:
python
# Start with one selector, verify results, then add more
test_selector = 'h2' # Start simple
headlines = soup.find_all(test_selector)
RSS Feeds: Most news sites have RSS feeds (check for /rss or /feed)
Pre-built datasets: Kaggle, GitHub have many news datasets
If You Must Scrape
Add these best practices:
python
# Enhanced version with better practices
import requests
from bs4 import BeautifulSoup
import time
from fake_useragent import UserAgent # pip install fake-useragent
def respectful_scraper(url, selectors):
"""Scraper with best practices"""
# Rotate user agents
ua = UserAgent()
headers = {'User-Agent': ua.random}
try:
# Respectful delay (start with 3-5 seconds)
time.sleep(3)
# Add timeout
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status()
# Check if we got HTML
if 'text/html' not in response.headers.get('Content-Type', ''):
print("Warning: Response doesn't appear to be HTML")
return []
soup = BeautifulSoup(response.content, 'html.parser')
# Use specific selectors for the target site
headlines = []
for selector in selectors:
for element in soup.select(selector):
text = element.get_text(strip=True)
if text and len(text.split()) > 3: # At least 4 words
headlines.append(text)
return list(set(headlines)) # Remove duplicates
except Exception as e:
print(f"Error: {e}")
return []
# Example for a hypothetical site
# selectors = ['h1.headline', 'h2.title', '.article h3']
# results = respectful_scraper('https://example-news.com', selectors)
Quick Start for Educational Purposes
For learning purposes only, here's a minimal version to understand the concept:
python
import requests
from bs4 import BeautifulSoup
url = "https://example.com/news" # REPLACE with a site that allows scraping
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Print all headings (will include non-news headings too)
for tag in soup.find_all(['h1', 'h2', 'h3']):
print(tag.get_text().strip())
Remember:
Start small: Test on 1-2 pages first
Check rate limits: Don't make dozens of requests per minute
Cache results: Don't re-scrape the same content repeatedly
Respect copyright: Don't republish content without permission
Use APIs when available: They're more reliable and legal
Would you like help with:
Finding the correct CSS selectors for a specific site (after you've verified it's allowed)?
Setting up a more robust scraper with error handling?
Learning how to use an official news API instead?
import requests
from bs4 import BeautifulSoup
import time
def scrape_news_headlines(url, delay=2):
"""
Scrape headlines from a news website homepage
Args:
url (str): URL of the news website homepage
delay (int): Delay between requests in seconds (be respectful)
Returns:
list: List of headline dictionaries with text and link
"""
# Set headers to mimic a real browser
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:
# Add delay to be respectful to the server
time.sleep(delay)
# Fetch the webpage
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status() # Raise an exception for bad status codes
# Parse HTML
soup = BeautifulSoup(response.content, 'html.parser')
headlines = []
# COMMON SELECTORS FOR NEWS HEADLINES (you need to inspect the actual site)
# These are examples - YOU MUST INSPECT THE TARGET SITE to find correct selectors
# Example 1: Generic headline selectors (adjust based on actual site structure)
headline_tags = soup.find_all(['h1', 'h2', 'h3', 'h4'])
for tag in headline_tags:
# Look for links within headlines (most headlines are clickable)
link = tag.find('a')
if link and link.get('href'):
headline_text = tag.get_text(strip=True)
if headline_text and len(headline_text) > 10: # Filter out very short text
headlines.append({
'text': headline_text,
'link': link['href'] if link['href'].startswith('http') else url + link['href'],
'tag': tag.name
})
# Example 2: Using class-based selectors (common patterns)
# You need to inspect the specific site to find these
common_classes = [
'headline', 'title', 'entry-title', 'post-title',
'article-title', 'news-title', 'story-title'
]
for class_name in common_classes:
elements = soup.find_all(class_=class_name)
for element in elements:
text = element.get_text(strip=True)
if text and len(text) > 10:
link = element.find('a')
headlines.append({
'text': text,
'link': link['href'] if link and link.get('href') else None,
'class': class_name
})
# Remove duplicates (based on text similarity)
unique_headlines = []
seen_texts = set()
for headline in headlines:
# Simple deduplication (you might need more sophisticated)
if headline['text'] not in seen_texts:
seen_texts.add(headline['text'])
unique_headlines.append(headline)
return unique_headlines
except requests.RequestException as e:
print(f"Error fetching the page: {e}")
return []
except Exception as e:
print(f"An error occurred: {e}")
return []
def main():
# EXAMPLE USAGE - REPLACE WITH ACTUAL SITE
# WARNING: Only use sites that allow scraping!
# Example sites that might work (but CHECK robots.txt first):
# - https://news.ycombinator.com (Hacker News - often used for examples)
# - Some government/news sites that explicitly allow scraping
# For demonstration, I'll use a sample HTML structure instead
# of a real site to avoid potential issues
print("=" * 60)
print("NEWS HEADLINE SCRAPER")
print("=" * 60)
print("\nNOTE: Before using on a real website:")
print("1. Check robots.txt (e.g., https://example.com/robots.txt)")
print("2. Review Terms of Service")
print("3. Add proper delays between requests")
print("4. Consider using official APIs if available\n")
# Example with a sample HTML (for demonstration only)
sample_html = """
<!DOCTYPE html>
<html>
<head><title>Sample News Site</title></head>
<body>
<h1 class="main-title">Breaking: Major News Event Happens</h1>
<div class="article">
<h2 class="headline"><a href="/story1">Important Local Story</a></h2>
<p>Lorem ipsum...</p>
</div>
<div class="article">
<h3 class="entry-title">International News Update</h3>
</div>
<div class="post">
<h4 class="post-title">Sports Championship Results</h4>
</div>
</body>
</html>
"""
# For demo purposes, parse this sample
soup = BeautifulSoup(sample_html, 'html.parser')
# In real usage, you would do:
# url = input("Enter news website URL: ").strip()
# headlines = scrape_news_headlines(url)
# For this demo, extract from sample
headlines = []
for tag in soup.find_all(['h1', 'h2', 'h3', 'h4']):
text = tag.get_text(strip=True)
if text:
link = tag.find('a')
headlines.append({
'text': text,
'link': link['href'] if link and link.get('href') else None,
'tag': tag.name
})
print("Sample headlines found:")
print("-" * 40)
for i, headline in enumerate(headlines, 1):
print(f"{i}. {headline['text']}")
if headline['link']:
print(f" Link: {headline['link']}")
print()
print("\n" + "=" * 60)
print("TO USE ON A REAL SITE:")
print("1. Inspect the website (right-click → Inspect)")
print("2. Find HTML patterns for headlines")
print("3. Update the selectors in the code")
print("4. TEST THOROUGHLY on small scale first")
print("=" * 60)
if __name__ == "__main__":
main()