Skriv en Python-funktion som heter get_dn_headlines.
Funktionen ska:
Använda biblioteken requests och BeautifulSoup4 för att hämta innehållet från Dagens Nyheters förstasida (https://www.dn.se).
Identifiera och extrahera texten från de primära artikelrubrikerna. Eftersom webbsidors struktur ändras, välj en logisk metod för att hitta dem (t.ex. genom att leta efter h2-taggar med en specifik klass som ofta används för rubriker).
Returnera en lista med de extraherade rubrikerna som strängar.
Inkludera felhantering för:
Nätverksfel (om requests misslyckas).
Situationen där inga rubriker hittas (t.ex. om DN ändrar sin HTML-struktur). I detta fall ska funktionen returnera en tom lista.
Koden ska vara välstrukturerad och kommenterad på engelska.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Här är en Python-funktion get_dn_headlines som uppfyller dina krav. Den använder requests för att hämta webbsidan och BeautifulSoup för att analysera HTML-innehållet och extrahera rubrikerna.
Viktig anmärkning: Webbsidors HTML-struktur kan ändras över tid. Koden nedan försöker hitta rubriker baserat på en antagen vanlig struktur för nyhetssidor (h2 eller h3 taggar med en klass som teaser__heading eller liknande). Om Dagens Nyheter ändrar sin HTML-kod, kan det hända att du behöver justera selektorerna ('h2', 'h3', class_='...') i soup.find_all() för att funktionen ska fortsätta fungera korrekt.
python
import requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException # For network error handling
def get_dn_headlines():
"""
Fetches the content from Dagens Nyheter's front page,
identifies and extracts primary article headlines.
Returns:
list: A list of extracted headlines as strings.
Returns an empty list if network error occurs or no headlines are found.
"""
url = "https://www.dn.se"
headlines = [] # Initialize an empty list to store the headlines
print(f"Attempting to fetch headlines from: {url}")
try:
# Send a GET request to the URL. Added a timeout for robustness.
response = requests.get(url, timeout=10)
# Raise an HTTPError for bad responses (4xx or 5xx)
response.raise_for_status()
except RequestException as e:
# Handle network-related errors (e.g., connection refused, timeout, DNS error)
print(f"Error fetching page from {url}: {e}")
return [] # Return empty list on network error
print("Successfully fetched the page. Parsing HTML...")
# Parse the HTML content using BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# --- Headline Extraction Strategy ---
# News websites often use <h2> or <h3> tags for primary headlines,
# frequently with specific CSS classes indicating they are article teasers/headings.
# 'teaser__heading' is a common pattern observed on many news sites (including previous DN versions).
# We look for both h2 and h3 tags that have this class.
# If this specific class changes or is not comprehensive,
# a broader search (e.g., just `soup.find_all(['h2', 'h3'])` and then filtering)
# or a different class/selector might be needed.
# Find all h2 and h3 tags with the class 'teaser__heading'
# This targets common prominent article headlines on news sites.
headline_elements = soup.find_all(['h2', 'h3'], class_='teaser__heading')
if not headline_elements:
# Fallback if the above specific class doesn't yield results.
# This is a less precise but broader search for any h2/h3 in the body.
# This might pick up some non-primary headings but is a safeguard.
print("No headlines found with 'teaser__heading' class. Attempting broader search for h2/h3 tags.")
headline_elements = soup.find_all(['h2', 'h3'])
for element in headline_elements:
# Get the text content of the element and strip leading/trailing whitespace
headline_text = element.get_text(strip=True)
if headline_text: # Ensure the extracted text is not empty
headlines.append(headline_text)
# Error handling for no headlines found after parsing
if not headlines:
print("Warning: No primary headlines found. DN's HTML structure may have changed, or the selectors need adjustment.")
return [] # Return empty list if no headlines were extracted
print(f"Found {len(headlines)} headlines.")
return headlines
# --- Example Usage ---
if __name__ == "__main__":
dn_headlines = get_dn_headlines()
if dn_headlines:
print("\n--- Dagens Nyheter Headlines ---")
for i, headline in enumerate(dn_headlines):
print(f"{i+1}. {headline}")
else:
print("\nCould not retrieve Dagens Nyheter headlines.")