import requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
def get_dn_headlines():
"""
Fetches the front page of Dagens Nyheter (DN), extracts the main article
headlines, and returns them as a list of strings.
Uses requests to fetch the page and BeautifulSoup to parse the HTML.
Includes error handling for network issues and cases where no headlines
are found based on the current parsing strategy.
Returns:
list: A list of strings, where each string is a headline.
Returns an empty list [] if fetching fails or no headlines
are found.
"""
url = "https://www.dn.se"
# Using a User-Agent can sometimes prevent being blocked by websites.
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'}
timeout = 10 # Set a timeout for the request
try:
# Fetch the content from the URL
response = requests.get(url, headers=headers, timeout=timeout)
# Raise an exception for bad status codes (4xx or 5xx)
response.raise_for_status()
html_content = response.text
except RequestException as e:
# Handle network errors, connection issues, timeouts, bad status codes etc.
print(f"Error fetching the URL {url}: {e}")
return [] # Return empty list as requested on failure
# Parse the HTML content
soup = BeautifulSoup(html_content, 'html.parser')
headlines = []
# --- Headline Extraction Strategy ---
# Websites frequently change their structure (HTML tags, classes).
# A common pattern for main article headlines on modern news sites
# is using <h2> or <h3> tags within article links or containers.
# Inspecting DN's structure often shows main headlines within <h2>
# tags that have a specific class name, sometimes containing a
# descriptive part like "StyledHeading" or "Heading" combined with
# potentially auto-generated strings.
# We'll search for <h2> tags and filter by a class name that
# is likely to indicate a headline. Using a lambda function for the
# `class_` argument allows checking if the class string contains a
# specific substring like 'StyledHeading'. This is a heuristic and
# might need adjustment if DN significantly changes its layout.
# Find all <h2> tags that have a class containing 'StyledHeading'
# This is a common pattern for the main visible headlines.
headline_elements = soup.find_all('h2', class_=lambda c: c and 'StyledHeading' in c)
if not headline_elements:
# Handle the case where the expected elements are not found.
# This happens if DN changes its HTML structure or if the page
# didn't load as expected (though requests.raise_for_status()
# should catch many loading issues).
print("Warning: Could not find elements matching the expected headline structure (h2 with class containing 'StyledHeading'). DN's website structure may have changed.")
# Return empty list as requested if no headlines could be extracted.
return []
# Extract the text from the found elements
for element in headline_elements:
# Get the text content of the element and remove leading/trailing whitespace
headline_text = element.get_text().strip()
if headline_text: # Add only if the extracted text is not empty
headlines.append(headline_text)
return headlines
# --- Example Usage ---
if __name__ == "__main__":
print("Attempting to fetch headlines from DN.se...")
dn_headlines = get_dn_headlines()
if dn_headlines:
print("\n--- Dagens Nyheter Headlines ---")
for i, headline in enumerate(dn_headlines, 1):
print(f"{i}. {headline}")
print("---------------------------------")
else:
print("\nCould not retrieve any headlines.")
print("This might be due to a network error or a change in DN's website structure.")