惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
P
Privacy International News Feed
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
N
Netflix TechBlog - Medium
S
Security Affairs
Spread Privacy
Spread Privacy
罗磊的独立博客
腾讯CDC
MyScale Blog
MyScale Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 热门话题
The Cloudflare Blog
L
LangChain Blog
博客园_首页
H
Hacker News: Front Page
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
SecWiki News
SecWiki News
A
Arctic Wolf
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
T
Tailwind CSS Blog
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Automating Web Intelligence with Python: A Practical Guide
James · 2026-05-14 · via DEV Community

Automating Web Intelligence with Python: A Practical Guide

Web intelligence — the systematic extraction of actionable data from the web — sounds like a spy movie plot. In reality, it's a Python script with good error handling and a respectful rate limit.

I run an agency in Berlin that builds this infrastructure for European clients. Here's the practical stack we use.


Pattern 1: Structured Data Extraction

The simplest and most common pattern: a website has predictable HTML structure, and you want specific fields.

import requests
from bs4 import BeautifulSoup
import time

def extract_product(url):
    headers = {
        "User-Agent": "GrahamMirandaBot/1.0 (+https://grahammiranda.com/scraping-policy)"
    }
    response = requests.get(url, headers=headers, timeout=30)
    soup = BeautifulSoup(response.text, "html.parser")

    return {
        "title": soup.select_one("h1.product-title").get_text(strip=True),
        "price": soup.select_one("span.price").get_text(strip=True),
        "availability": soup.select_one("div.availability").get_text(strip=True),
        "url": url,
        "scraped_at": time.strftime("%Y-%m-%d %H:%M:%S")
    }

# Usage
for url in product_urls:
    data = extract_product(url)
    save_to_database(data)
    time.sleep(1.0)  # Respectful rate limiting

Enter fullscreen mode Exit fullscreen mode

When this works: E-commerce product pages, directory listings, news article pages — any site with consistent CSS classes.

When it breaks: Sites using JavaScript frameworks (React, Vue) where content loads after initial HTML.


Pattern 2: Dynamic Content with Playwright

For JS-rendered sites, you need a real browser. Playwright is the current standard.

from playwright.sync_api import sync_playwright
import time

def extract_dynamic(url):
    with sync_playwright() as p:
        browser = p.firefox.launch(headless=True)
        page = browser.new_page()

        # Anti-detection
        page.add_init_script("""
            Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
        """)

        page.goto(url, wait_until="networkidle")
        time.sleep(2)  # Wait for JS hydration

        # Extract after render
        title = page.locator("h1").inner_text()
        price = page.locator("[data-testid='price']").inner_text()

        browser.close()
        return {"title": title, "price": price, "url": url}

Enter fullscreen mode Exit fullscreen mode

Key insight: wait_until="networkidle" waits for network activity to cease — essential for SPAs. But on heavy pages, this can take 10+ seconds. Use domcontentloaded + fixed sleep for faster processing.

Cost: ~3-5x slower than requests/BeautifulSoup. Use only when necessary.


Pattern 3: API Aggregation

Many sites expose JSON APIs that are easier to parse than HTML. Finding them:

import requests

# Method 1: Check page source for API calls
response = requests.get("https://example.com/products")
# Look for `window.__INITIAL_STATE__` or similar JS variables

# Method 2: Network inspection (manual, then script)
# Open DevTools → Network → XHR → find the API endpoint
# Usually: /api/v1/products, /graphql, /json/products

# Method 3: Check for GraphQL endpoints
# Common patterns: /graphql, /api/graphql, /gql

Enter fullscreen mode Exit fullscreen mode

The real value: APIs return structured data. No HTML parsing needed. Much more reliable.


Pattern 4: Distributed Crawling at Scale

For thousands of URLs, you need a queue system.

from celery import Celery
import redis

app = Celery('web_intel', broker='redis://localhost:6379/0')
redis_client = redis.Redis(host='localhost', port=6379, db=1)

@app.task
def scrape_url(url):
    # Your extraction logic here
    data = extract_product(url)
    redis_client.hset(f"product:{url}", mapping=data)
    return data

# Queue 10,000 URLs
for url in url_list:
    scrape_url.delay(url)

Enter fullscreen mode Exit fullscreen mode

Architecture:

  • Redis: URL queue + result cache
  • Celery workers: 4-8 parallel scrapers
  • PostgreSQL: Persistent storage
  • Monitoring: Flower (Celery dashboard) + Prometheus

Scaling rule: One worker per CPU core. With rate limiting at 1 req/sec, 8 workers = 8 req/sec sustained throughput.


Pattern 5: Document Parsing

Web intelligence isn't just web pages. Documents matter too.

# PDF extraction
import fitz  # PyMuPDF

def extract_pdf_text(url):
    response = requests.get(url)
    doc = fitz.open(stream=response.content, filetype="pdf")
    text = "\n".join(page.get_text() for page in doc)
    return text

# DOCX extraction
from docx import Document

def extract_docx_text(filepath):
    doc = Document(filepath)
    return "\n".join(p.text for p in doc.paragraphs)

Enter fullscreen mode Exit fullscreen mode

Use case: Legal discovery, contract analysis, regulatory document monitoring.


Error Handling That Matters

The difference between a prototype and production scraping is error handling.

def robust_extract(url, max_retries=3):
    for attempt in range(max_retries):
        try:
            return extract_product(url)
        except requests.exceptions.Timeout:
            time.sleep(5 * (attempt + 1))  # Exponential backoff
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 429:
                time.sleep(60)  # Rate limited — long wait
            elif e.response.status_code == 403:
                return {"error": "blocked", "url": url}
            else:
                raise
        except Exception as e:
            if attempt == max_retries - 1:
                return {"error": str(e), "url": url}
            time.sleep(2 ** attempt)

    return {"error": "max_retries_exceeded", "url": url}

Enter fullscreen mode Exit fullscreen mode

Critical patterns:

  • 429 (Too Many Requests): Back off for 60+ seconds
  • 403 (Forbidden): Switch proxy or skip
  • 502/503/504: Retry with exponential backoff
  • Connection timeout: Retry with longer timeout
  • Parse error: Log and continue (don't crash the batch)

Rate Limiting: The Non-Negotiable Rule

import time
from functools import wraps

def rate_limited(max_per_second=1.0):
    min_interval = 1.0 / max_per_second
    last_called = [0.0]

    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            elapsed = time.time() - last_called[0]
            if elapsed < min_interval:
                time.sleep(min_interval - elapsed)
            result = fn(*args, **kwargs)
            last_called[0] = time.time()
            return result
        return wrapper
    return decorator

@rate_limited(max_per_second=0.5)  # 1 request per 2 seconds
def fetch_url(url):
    return requests.get(url, timeout=30)

Enter fullscreen mode Exit fullscreen mode

Our defaults:

  • General sites: 1 req/sec
  • Small sites (< 100 pages): 0.5 req/sec
  • APIs with documented limits: Follow documented limit minus 10%
  • German government sites: 0.2 req/sec (extra polite)

DSGVO Compliance Checklist

For every scraping project:

  • [ ] robots.txt checked and respected
  • [ ] Public data only (no login-required pages)
  • [ ] No personal data collected (names, emails, addresses stripped)
  • [ ] Rate limiting implemented
  • [ ] User-Agent identifies scraper with contact info
  • [ ] Data retention policy defined (default: 90 days)
  • [ ] Audit trail maintained
  • [ ] Legitimate Interest assessment documented

Tools We Recommend

Tool Purpose Cost
requests + BeautifulSoup Simple HTML scraping Free
Playwright JS-rendered sites Free
Scrapy Large-scale crawling Free
Celery + Redis Distributed queue Free
PostgreSQL Structured storage Free
Elasticsearch Full-text search Free
Hetzner VPS Hosting €6–15/month
Bright Data / Oxylabs Residential proxies $50–500/month

Real-World Example

Client: Hamburg logistics company
Goal: Monitor shipping lane disruptions from port authority websites
Scope: 15 port authorities across Europe, updated every 6 hours
Implementation:

  • Scrapy spider with rotating User-Agents
  • Celery beat schedule (6-hour intervals)
  • Redis for deduplication
  • Telegram notification on status changes
  • DSGVO compliance: Public data only, 30-day retention

Result: Detected a Rotterdam strike 4 hours before mainstream news. Client rerouted 3 containers, saving €12,000 in demurrage fees.


Resources


Graham Miranda is the founder of Graham Miranda UG (Berlin, HRB 36794), specializing in web intelligence, automation, and privacy-first infrastructure for European businesses.