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

推荐订阅源

AI
AI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google DeepMind News
Google DeepMind News
T
Tenable Blog
博客园_首页
S
Securelist
Spread Privacy
Spread Privacy
Google Online Security Blog
Google Online Security Blog
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
U
Unit 42
L
LINUX DO - 热门话题
量子位
T
Threat Research - Cisco Blogs
博客园 - 【当耐特】
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
Martin Fowler
Martin Fowler
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
V
Vulnerabilities – Threatpost
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
I
InfoQ
Know Your Adversary
Know Your Adversary
Cisco Talos Blog
Cisco Talos Blog
The Register - Security
The Register - Security
T
The Blog of Author Tim Ferriss
aimingoo的专栏
aimingoo的专栏
V2EX - 技术
V2EX - 技术
T
Tailwind CSS Blog
月光博客
月光博客
Recent Announcements
Recent Announcements
G
Google Developers Blog
F
Full Disclosure
W
WeLiveSecurity
宝玉的分享
宝玉的分享
腾讯CDC
G
GRAHAM CLULEY
Vercel News
Vercel News
Simon Willison's Weblog
Simon Willison's Weblog
美团技术团队
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Help Net Security
Help Net Security

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
Selectolax: a faster BeautifulSoup alternative for Python scraping at scale
Oriol Martí · 2026-05-20 · via DEV Community

Our API was choking at 2 requests per second. Not because of network. Not because of proxies. The CPU was at 100% just parsing HTML.

We run FlyByAPIs, a set of web scraping APIs. One of our heaviest endpoints parses full e-commerce product pages: dozens of fields, nested sections, fallback selectors for when the site A/B tests its layout. We were using Parsel (which wraps lxml under the hood), and it worked fine. Until we needed concurrency.

At 2-5 parallel requests, CPU was saturated. Parsing alone was eating 150-200ms per page. Multiply that by concurrent workers sharing the same CPU and you've got a bottleneck that no proxy optimization will fix.

We switched to Selectolax. Parsing dropped to 30-40ms. Went from 2-5 req/s to 15-20 req/s on the same hardware.

What is Selectolax?

Selectolax is a Python binding for the Lexbor HTML parser. Lexbor is a C library built from scratch for speed. It implements the HTML5 spec and supports CSS selectors.

Why is it faster? BeautifulSoup and Parsel build a full Python object tree. Every node becomes a Python object with attributes, methods, navigation helpers. That's convenient if you need to manipulate the DOM, but it's expensive when all you want is to read values out. Selectolax keeps the parsed tree in C memory and only creates Python objects when you actually access a node. Way less memory allocation and garbage collection pressure.

pip install selectolax

Enter fullscreen mode Exit fullscreen mode

No extra dependencies. Works on Linux, macOS, Windows.

The basics: BeautifulSoup vs Selectolax

If you've used BeautifulSoup, Selectolax will feel familiar. The API is smaller, but it covers what you actually need for scraping.

BeautifulSoup:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "lxml")
title = soup.select_one("h1.product-title")
print(title.get_text(strip=True))

prices = soup.select("span.price")
for p in prices:
    print(p.get_text(strip=True))

Enter fullscreen mode Exit fullscreen mode

Selectolax:

from selectolax.lexbor import LexborHTMLParser

tree = LexborHTMLParser(html)
title = tree.css_first("h1.product-title")
print(title.text(deep=False).strip())

prices = tree.css("span.price")
for p in prices:
    print(p.text(deep=False).strip())

Enter fullscreen mode Exit fullscreen mode

select_one becomes css_first. select becomes css. .get_text() becomes .text(). For attributes: node.attributes.get("href") instead of node["href"].

One gotcha: text(deep=False) returns only the direct text of that node, not its children. This is actually useful when you're parsing structured pages where a parent element contains multiple text nodes you want to extract separately. Use text(deep=True) (the default) when you want all nested text.

Where it actually matters: CPU under concurrency

Most benchmark numbers you see online ("selectolax is 5x faster than BS4!") are measured on a single thread, single document. Cool. But that misses the real problem.

In production, if you're running an async framework like FastAPI/uvicorn, your request handlers share a single event loop. HTML parsing is synchronous, CPU-bound work. While Parsel spends 150ms parsing one page, the event loop is blocked. Every other request just sits there waiting. It doesn't matter that your code is async, the parsing step isn't.

The faster the parse, the less time you block the loop, the more requests you can actually handle concurrently. That's why the throughput gain is bigger than the raw per-document speed improvement suggests.

Before the switch, our monitoring showed CPU at 95-100% during peak traffic. Request latency was spiking because the event loop was constantly blocked by parsing. After the switch, CPU sits around 40-50% under the same load. Same hardware. Same traffic.

Scoped selectors (nested parents)

This is the optimization that made the biggest difference after the parser swap itself.

A typical product page has 40-60 fields to extract. If you run every CSS selector from the document root, the parser traverses the entire DOM tree for each field. On a 500KB HTML page with thousands of nodes, that adds up fast.

The idea is simple: scope your selectors. Grab the container element first, then query fields within that subtree.

Naive (slow):

tree = LexborHTMLParser(html)

# Every selector searches the entire document
title = tree.css_first("h1.product-title")
price = tree.css_first("#price-section .current-price")
seller = tree.css_first("#seller-info .seller-name")
stock = tree.css_first("#seller-info .stock-status")
rating = tree.css_first("#reviews .star-rating")
review_count = tree.css_first("#reviews .total-reviews")

Enter fullscreen mode Exit fullscreen mode

Scoped (fast):

tree = LexborHTMLParser(html)

# Level 1: grab major page sections
seller_section = tree.css_first("#seller-info")
review_section = tree.css_first("#reviews")

# Level 2: query within the scoped subtree
title = tree.css_first("h1.product-title")  # still from root (only one on page)
price = tree.css_first("#price-section .current-price")

if seller_section:
    seller = seller_section.css_first(".seller-name")
    stock = seller_section.css_first(".stock-status")
    delivery = seller_section.css_first(".delivery-estimate")

if review_section:
    rating = review_section.css_first(".star-rating")
    review_count = review_section.css_first(".total-reviews")
    # Level 3: individual review cards within the review section
    for card in review_section.css(".review-card"):
        author = card.css_first(".author-name")
        text = card.css_first(".review-text")
        stars = card.css_first(".star-count")

Enter fullscreen mode Exit fullscreen mode

You go two or three levels deep. Document to section to element to sub-element. Each level narrows the DOM subtree the parser needs to traverse. With 50+ selectors per page, this compounds quickly.

In our case, this shaved another 20-30% off parsing time on top of the Selectolax speed gain.

Fallback selectors

Websites change their HTML. Constantly. The field that lived in span.a-price .a-offscreen last week might be in .price-block .current this week. If you hardcode a single selector, your scraper breaks silently, returns None instead of a price, and nobody notices until a customer complains.

We use fallback selectors:

def select_one_with_fallbacks(node, primary_selector, fallbacks=None):
    result = node.css_first(primary_selector)
    if result is not None:
        return result
    for fallback in (fallbacks or []):
        result = node.css_first(fallback)
        if result is not None:
            return result
    return None

# Usage
price_node = select_one_with_fallbacks(
    tree,
    "span.current-price .amount",
    fallbacks=[
        ".price-block .a-offscreen",
        "#price .display-price",
    ]
)

Enter fullscreen mode Exit fullscreen mode

The primary selector is the one that works today. The fallbacks are selectors that worked in previous versions of the page, or alternative ones we've seen on different page variants (A/B tests, regional differences).

This works well with Selectolax because each css_first call is cheap. You're trying 2-3 selectors instead of 1, but at microsecond cost per attempt, it's negligible. With BeautifulSoup, the overhead per selector is higher and you'd feel it more.

We actually define all our selectors in YAML config files, not in code. When a site changes its layout, we update a config file and deploy. No code changes, no test rewrites. When you run scraping at scale, data drift is your biggest enemy, and having selectors in config instead of code means you can react in minutes instead of hours. But that deserves its own post.

When Selectolax is NOT the right choice

Selectolax isn't always the answer.

If you need to modify the HTML tree (insert nodes, delete nodes, change attributes), stick with BeautifulSoup. Selectolax is read-only.

For one-off scripts where speed doesn't matter, BeautifulSoup is more forgiving and better documented. More Stack Overflow answers too.

If you need XPath, use Parsel or lxml. Selectolax only does CSS selectors. Same if you're deep in a Scrapy pipeline, Parsel is native there and the integration is tight.

Where Selectolax wins: when you're parsing HTML inside a web server or API that handles concurrent requests. When CPU is your actual bottleneck. When CSS selectors are enough (which, honestly, covers 95% of scraping use cases).

Migration cheat sheet

If you're moving from BS4 or Parsel:

BeautifulSoup / Parsel Selectolax
soup.select("div.item") tree.css("div.item")
soup.select_one("h1") tree.css_first("h1")
tag.get_text(strip=True) node.text(deep=False).strip()
tag["href"] node.attributes.get("href")
tag.get("href", "") node.attributes.get("href") or ""
tag.find_parent("div") node.parent (then check tag)
len(soup.select("li")) len(tree.css("li"))

Watch out for None. If css_first doesn't find anything, calling .text() on it will crash. Always guard:

node = tree.css_first("h1.title")
title = node.text(deep=False).strip() if node else None

Enter fullscreen mode Exit fullscreen mode

Our numbers

Before/after on the same hardware, parsing full e-commerce product detail pages (50+ fields each):

Metric Parsel (lxml) Selectolax (Lexbor)
Parse time per page ~150-200ms ~30-40ms
Max concurrent req/s before CPU saturation 2-5 15-20
CPU usage at peak load 95-100% 40-50%
Memory per parsed page Higher (Python objects) Lower (C-level tree)

The throughput gain is larger than the raw parse-time improvement because of the event loop blocking I mentioned. Less time parsing means less time blocking the loop, which means more time for network I/O, JSON serialization, everything else.

So, what did we learn

We spent weeks optimizing proxy rotation and connection pooling before we realized the bottleneck was HTML parsing. Weeks. If you're building scrapers or data extraction services and you're hitting CPU limits, check your parser before throwing more infrastructure at it.

The migration took us about a day for the core parser, plus another day fixing edge cases across all our endpoints. Not bad for a 5x improvement.

pip install selectolax, swap one parser, benchmark it. You'll see it.

We use Selectolax across all of our Amazon API endpoints. 50+ fields per page, 22 marketplaces, sub-second response times. The entire parsing layer runs on it.

If you've dealt with similar parsing bottlenecks, or you're in the middle of a migration, I'd love to hear how it went.