o4-mini-2025-04-16· OpenAI
LMArena Human Preference 140K
script to scrap websites
- User
script to scrap websites
- Assistant
Here’s a simple, reusable Python “boilerplate” that shows you how to scrape most static websites using requests and BeautifulSoup. Feel free to adapt it to your needs (different selectors, pagination, output format, etc.)—and please respect each site’s robots.txt and terms of service!
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Simple web-scraper template using requests + BeautifulSoup. - Installs: pip install requests beautifulsoup4 - Usage: python scrape.py """ import requests from bs4 import BeautifulSoup import time import csv import logging import sys # ————— CONFIG ————— HEADERS = { "User-Agent": "MyScraperBot/1.0 (+https://mywebsite.example/)" } START_URL = "https://example.com/articles" OUTPUT_CSV = "results.csv" DELAY_BETWEEN_REQUESTS = 1.0 # seconds # ———————————– logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stdout)] ) def fetch_page(url): """Fetch HTML content and return a BeautifulSoup object.""" logging.info(f"GET {url}") resp = requests.get(url, headers=HEADERS, timeout=10) resp.raise_for_status() return BeautifulSoup(resp.text, "html.parser") def parse_list_page(soup): """ Extract article links (or other items) from a listing page. Return a list of URLs (absolute or relative). """ links = [] for a in soup.select("div.article-preview > a"): href = a.get("href") if href: # Make URL absolute if needed: links.append(requests.compat.urljoin(START_URL, href)) logging.info(f"Found {len(links)} articles on the page.") return links def parse_article_page(soup): """ Extract title, author, date, content, etc. Return a dict of the fields you care about. """ data = {} data["title"] = soup.select_one("h1.article-title").get_text(strip=True) data["author"] = soup.select_one("span.author-name").get_text(strip=True) data["date"] = soup.select_one("time.publish-date")["datetime"] data["body"] = "\n".join( p.get_text(strip=True) for p in soup.select("div.article-content p") ) return data def main(): all_articles = [] # 1) Fetch listing page (or paginate through many) soup = fetch_page(START_URL) article_urls = parse_list_page(soup) # 2) Loop through each article URL for url in article_urls: try: art_soup = fetch_page(url) info = parse_article_page(art_soup) info["url"] = url all_articles.append(info) except Exception as e: logging.error(f"Failed to parse {url}: {e}") time.sleep(DELAY_BETWEEN_REQUESTS) # 3) Save results to CSV if all_articles: keys = all_articles[0].keys() with open(OUTPUT_CSV, "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=keys) writer.writeheader() writer.writerows(all_articles) logging.info(f"Saved {len(all_articles)} items to {OUTPUT_CSV}") else: logging.warning("No data scraped.") if __name__ == "__main__": main()How to customize:
- Change
START_URLto the page you want to scrape. - Inspect the HTML with your browser’s DevTools and adjust the CSS selectors in
parse_list_pageandparse_article_page. - For multi-page scrapes, add a loop around
START_URL(e.g.for page in range(1,5): … START_URL.format(page=page)). - If the site uses JavaScript to render content, consider using Selenium (or Playwright) instead of requests.
- Always check
robots.txtand the site’s Terms of Service before scraping, and throttle your requests (we used a 1 sec delay).
Enjoy your scraping—and scrape responsibly! 🚀
- Change
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.