Scrape and summarize news using Hugging Face Transformers with a distilbart-cnn model…
- User
Scrape and summarize news using Hugging Face Transformers with a distilbart-cnn model for abstractive summarization. Parse main content using readability-lxml to strip ads and navbars before feeding text to the model.
- Assistant
Preparing safe news scraping and summarization code
I'm creating a Python example that fetches webpage HTML via requests, extracts main content using readability-lxml, then summarizes it with Hugging Face's distilbart-cnn model via transformers pipeline—while noting to respect site policies and including error handling. Here's a minimal end‑to‑end example in Python that pulls an article, uses
readability-lxmlto extract the main body text, and then feeds that into a distilbart‑cnn summarization model from Hugging Face:pip install requests readability-lxml transformers torchimport requests from readability import Document from transformers import pipeline def fetch_main_text(url: str) -> str: """ Fetch a URL and extract the main content using readability-lxml. """ resp = requests.get(url, timeout=10) resp.raise_for_status() doc = Document(resp.text) # doc.title() will give you the headline if you need it html = doc.summary(html_partial=True) # Strip HTML tags and normalize whitespace from bs4 import BeautifulSoup soup = BeautifulSoup(html, "html.parser") text = soup.get_text(separator="\n", strip=True) return text def summarize(text: str, max_length: int = 130, min_length: int = 30) -> str: """ Summarize the given text using distilbart-cnn. """ summarizer = pipeline( "summarization", model="sshleifer/distilbart-cnn-12-6", tokenizer="sshleifer/distilbart-cnn-12-6", ) # The model expects relatively short inputs; chunk if necessary return summarizer( text, max_length=max_length, min_length=min_length, do_sample=False, truncation=True, )[0]["summary_text"] if __name__ == "__main__": url = "https://example.com/some/news/article" article_text = fetch_main_text(url) print("Original length:", len(article_text.split())) summary = summarize(article_text) print("Summary:\n", summary)A few tips:
readability.Documentpulls out the main body and strips navbars/ads, but you can adjust its settings if needed.distilbart-cnnis trained on CNN/Daily Mail articles; for best results, keep inputs under a couple thousand tokens. For very long articles, split into chunks and summarize each chunk.- Always respect the target site's terms of service and robots.txt when scraping.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.