tinycodinglm / code /appdev-0015.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.25 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

Walk me through building a web scraper: key concepts, concrete details and common pitfalls. Include a runnable code example with its expected output.

Assistant

Web Scraper (using requests + BeautifulSoup):

python
import requests
from bs4 import BeautifulSoup
import json
import time

def scrape_hn(top_n=30):
    """Scrape Hacker News front page."""
    url = 'https://news.ycombinator.com/'
    resp = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
    soup = BeautifulSoup(resp.text, 'html.parser')

    articles = []
    for item in soup.select('.titleline > a')[:top_n]:
        articles.append({
            'title': item.get_text(),
            'url': item.get('href', ''),
        })
    return articles

def scrape_with_retry(url, max_retries=3):
    """Scrape with retry logic."""
    for attempt in range(max_retries):
        try:
            resp = requests.get(url, timeout=10)
            resp.raise_for_status()
            return BeautifulSoup(resp.text, 'html.parser')
        except requests.RequestException as e:
            print(f'Attempt {attempt+1} failed: {e}')
            time.sleep(2 ** attempt)
    return None

if __name__ == '__main__':
    articles = scrape_hn()
    for i, a in enumerate(articles, 1):
        print(f'{i}. {a["title"]}')
        print(f'   {a["url"]}\n')
    with open('hn_articles.json', 'w') as f:
        json.dump(articles, f, indent=2)

Best practices:

  • Respect robots.txt
  • Add delays between requests
  • Handle errors gracefully
  • Cache responses when possible