Skip to content
TheChatArchiveThe Chat Archive
o4-mini-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

script to scrap websites

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-flash-lite-preview-06-17-thinking’s answer.
  1. User

    script to scrap websites

  2. 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:

    1. Change START_URL to the page you want to scrape.
    2. Inspect the HTML with your browser’s DevTools and adjust the CSS selectors in parse_list_page and parse_article_page.
    3. For multi-page scrapes, add a loop around START_URL (e.g. for page in range(1,5): … START_URL.format(page=page)).
    4. If the site uses JavaScript to render content, consider using Selenium (or Playwright) instead of requests.
    5. Always check robots.txt and the site’s Terms of Service before scraping, and throttle your requests (we used a 1 sec delay).

    Enjoy your scraping—and scrape responsibly! 🚀

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.