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

推荐订阅源

T
Tailwind CSS Blog
月光博客
月光博客
爱范儿
爱范儿
罗磊的独立博客
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
IT之家
IT之家
aimingoo的专栏
aimingoo的专栏
D
DataBreaches.Net
F
Full Disclosure
博客园 - 司徒正美
小众软件
小众软件
D
Docker
大猫的无限游戏
大猫的无限游戏
O
OpenAI News
T
Threatpost
Engineering at Meta
Engineering at Meta
Cisco Talos Blog
Cisco Talos Blog
Google DeepMind News
Google DeepMind News
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Y
Y Combinator Blog
H
Help Net Security
C
Cyber Attacks, Cyber Crime and Cyber Security
C
Cisco Blogs
The GitHub Blog
The GitHub Blog
S
SegmentFault 最新的问题
博客园 - 聂微东
A
Arctic Wolf
T
Threat Research - Cisco Blogs
U
Unit 42
NISL@THU
NISL@THU
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 【当耐特】
T
Troy Hunt's Blog
PCI Perspectives
PCI Perspectives
Webroot Blog
Webroot Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
AWS News Blog
AWS News Blog
The Last Watchdog
The Last Watchdog
Last Week in AI
Last Week in AI
V
Vulnerabilities – Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
腾讯CDC
V
V2EX
A
About on SuperTechFans
Know Your Adversary
Know Your Adversary
S
Security Affairs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

MarkTechPost

A Coding Implementation of End-to-End Brain Decoding from MEG Signals Using NeuralSet and Deep Learning for Predicting Linguistic Features Meta Introduces Autodata: An Agentic Framework That Turns AI Models into Autonomous Data Scientists for High-Quality Training Data Creation A Coding Guide on LLM Post Training with TRL from Supervised Fine Tuning to DPO and GRPO Reasoning Qwen AI Releases Qwen-Scope: An Open-Source Sparse AutoEncoders (SAE) Suite That Turns LLM Internal Features into Practical Development Tools A Coding Deep Dive into Agentic UI, Generative UI, State Synchronization, and Interrupt-Driven Approval Flows Moonshot AI Open-Sources FlashKDA: CUTLASS Kernels for Kimi Delta Attention with Variable-Length Batching and H20 Benchmarks Microsoft Research’s World-R1 Uses Flow-GRPO and 3D-Aware Rewards to Inject Geometric Consistency Into Wan 2.1 Without Architectural Changes A Coding Implementation on Pyright Type Checking Covering Generics, Protocols, Strict Mode, Type Narrowing, and Modern Python Typing IBM Releases Two Granite Speech 4.1 2B Models: Autoregressive ASR with Translation and Non-Autoregressive Editing for Fast Inference Top 10 KV Cache Compression Techniques for LLM Inference: Reducing Memory Overhead Across Eviction, Quantization, and Low-Rank Methods Qwen Team Releases FlashQLA: a High-Performance Linear Attention Kernel Library That Achieves Up to 3× Speedup on NVIDIA Hopper GPUs Step by Step Guide to Build a Complete PII Detection and Redaction Pipeline with OpenAI Privacy Filter Meta FAIR Releases NeuralSet: A Python Package for Neuro-AI That Supports fMRI, M/EEG, Spikes, and HuggingFace Embeddings smol-audio: A Colab-Friendly Notebook Collection for Fine-Tuning Whisper, Parakeet, Voxtral, Granite Speech, and Audio Flamingo 3 A Coding Implementation on Document Parsing Benchmarking with LlamaIndex ParseBench Using Python, Hugging Face, and Evaluation Metrics Poolside AI Introduces Laguna XS.2 and M.1: Agentic Coding Models Reaching 68.2% and 72.5% on SWE-bench Verified How to Build Traceable and Evaluated LLM Workflows Using Promptflow, Prompty, and OpenAI OpenAI Releases Privacy Filter: A 1.5B-Parameter Open-Source PII Redaction Model with 50M Active Parameters Top 10 Physical AI Models Powering Real-World Robots in 2026 How to Build a Lightweight Vision-Language-Action-Inspired Embodied Agent with Latent World Modeling and Model Predictive Control Meet Talkie-1930: A 13B Open-Weight LLM Trained on Pre-1931 English Text for Historical Reasoning and Generalization Research Build a Reinforcement Learning Powered Agent that Learns to Retrieve Relevant Long-Term Memories for Accurate LLM Question Answering OpenMOSS Releases MOSS-Audio: An Open-Source Foundation Model for Speech, Sound, Music, and Time-Aware Audio Reasoning Meta AI Releases Sapiens2: A High-Resolution Human-Centric Vision Model for Pose, Segmentation, Normals, Pointmap, and Albedo The LoRA Assumption That Breaks in Production How to Build a Fully Searchable AI Knowledge Base with OpenKB, OpenRouter, and Llama How to Build Smarter Multilingual Text Wrapping with BudouX Through Parsing, HTML Rendering, Model Introspection, and Toy Training Top 7 Benchmarks That Actually Matter for Agentic Reasoning in Large Language Models RAG Without Vectors: How PageIndex Retrieves by Reasoning A Coding Tutorial on Datashader on Rendering Massive Datasets with High-Performance Python Visual Analytics xAI Launches grok-voice-think-fast-1.0: Topping τ-voice Bench at 67.3%, Outperforming Gemini, GPT Realtime, and More A Coding Implementation on kvcached for Elastic KV Cache Memory, Bursty LLM Serving, and Multi-Model GPU Sharing Google DeepMind Introduces Vision Banana: An Instruction-Tuned Image Generator That Beats SAM 3 on Segmentation and Depth Anything V3 on Metric Depth Estimation Meet GitNexus: An Open-Source MCP-Native Knowledge Graph Engine That Gives Claude Code and Cursor Full Codebase Structural Awareness A Coding Implementation on Deepgram Python SDK for Transcription, Text-to-Speech, Async Audio Processing, and Text Intelligence A Coding Implementation on Microsoft’s OpenMementos with Trace Structure Analysis, Context Compression, and Fine-Tuning Data Preparation DeepSeek AI Releases DeepSeek-V4: Compressed Sparse Attention and Heavily Compressed Attention Enable One-Million-Token Contexts Google DeepMind Introduces Decoupled DiLoCo: An Asynchronous Training Architecture Achieving 88% Goodput Under High Hardware Failure Rates Mend Releases AI Security Governance Framework: Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model Mend.io Releases AI Security Governance Framework Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model OpenAI Releases GPT-5.5, a Fully Retrained Agentic Model That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval A Coding Tutorial on OpenMythos on Recurrent-Depth Transformers with Depth Extrapolation, Adaptive Computation, and Mixture-of-Experts Routing Google Cloud AI Research Introduces ReasoningBank: A Memory Framework that Distills Reasoning Strategies from Agent Successes and Failures Xiaomi Releases MiMo-V2.5-Pro and MiMo-V2.5: Matching Frontier Model Benchmarks at Significantly Lower Token Cost How to Design a Production-Grade CAMEL Multi-Agent System with Planning, Tool Use, Self-Consistency, and Critique-Driven Refinement Alibaba Qwen Team Releases Qwen3.6-27B: A Dense Open-Weight Model Outperforming 397B MoE on Agentic Coding Benchmarks A Detailed Implementation on Equinox with JAX Native Modules, Filtered Transforms, Stateful Layers, and End-to-End Training Workflows Next Leap to Harness Engineering: JiuwenClaw Pioneers ‘Coordination Engineering’ Photon Releases Spectrum: An Open-Source TypeScript Framework that Deploys AI Agents Directly to iMessage, WhatsApp, and Telegram OpenAI Open-Sources Euphony: A Browser-Based Visualization Tool for Harmony Chat Data and Codex Session Logs Hugging Face Releases ml-intern: An Open-Source AI Agent that Automates the LLM Post-Training Workflow A Coding Implementation to Build a Conditional Bayesian Hyperparameter Optimization Pipeline with Hyperopt, TPE, and Early Stopping Google Introduces Simula: A Reasoning-First Framework for Generating Controllable, Scalable Synthetic Datasets Across Specialized AI Domains A Coding Implementation on Qwen 3.6-35B-A3B Covering Multimodal Inference, Thinking Control, Tool Calling, MoE Routing, RAG, and Session Persistence Moonshot AI Releases Kimi K2.6 with Long-Horizon Coding, Agent Swarm Scaling to 300 Sub-Agents and 4,000 Coordinated Steps A Coding Implementation on Microsoft’s Phi-4-Mini for Quantized Inference Reasoning Tool Use RAG and LoRA Fine-Tuning OpenAI Scales Trusted Access for Cyber Defense With GPT-5.4-Cyber: a Fine-Tuned Model Built for Verified Security Defenders Moonshot AI and Tsinghua Researchers Propose PrfaaS: A Cross-Datacenter KVCache Architecture that Rethinks How LLMs are Served at Scale Meet OpenMythos: An Open-Source PyTorch Reconstruction of Claude Mythos Where 770M Parameters Match a 1.3B Transformer How TabPFN Leverages In-Context Learning to Achieve Superior Accuracy on Tabular Datasets Compared to Random Forest and CatBoost A Coding Implementation to Build an AI-Powered File Type Detection and Security Analysis Pipeline with Magika and OpenAI NVIDIA Releases Ising: the First Open Quantum AI Model Family for Hybrid Quantum-Classical Systems xAI Launches Standalone Grok Speech-to-Text and Text-to-Speech APIs, Targeting Enterprise Voice Developers A Coding Tutorial for Running PrismML Bonsai 1-Bit LLM on CUDA with GGUF, Benchmarking, Chat, JSON, and RAG A Coding Guide for Property-Based Testing Using Hypothesis with Stateful, Differential, and Metamorphic Test Design Anthropic Releases Claude Opus 4.7: A Major Upgrade for Agentic Coding, High-Resolution Vision, and Long-Horizon Autonomous Tasks Google AI Releases Auto-Diagnose: An Large Language Model LLM-Based System to Diagnose Integration Test Failures at Scale A End-to-End Coding Guide to Running OpenAI GPT-OSS Open-Weight Models with Advanced Inference Workflows Top 19 AI Red Teaming Tools (2026): Secure Your ML Models A Coding Guide to Build a Production-Grade Background Task Processing System Using Huey with SQLite, Scheduling, Retries, Pipelines, and Concurrency Control Qwen Team Open-Sources Qwen3.6-35B-A3B: A Sparse MoE Vision-Language Model with 3B Active Parameters and Agentic Coding Capabilities OpenAI Launches GPT-Rosalind: Its First Life Sciences AI Model Built to Accelerate Drug Discovery and Genomics Research Building Transformer-Based NQS for Frustrated Spin Systems with NetKet UCSD and Together AI Research Introduces Parcae: A Stable Architecture for Looped Language Models That Achieves the Quality of a Transformer Twice the Size How to Build a Universal Long-Term Memory Layer for AI Agents Using Mem0 and OpenAI A Coding Implementation to Build Multi-Agent AI Systems with SmolAgents Using Code Execution, Tool Calling, and Dynamic Orchestration A Technical Deep Dive into the Essential Stages of Modern Large Language Model Training, Alignment, and Deployment Google AI Launches Gemini 3.1 Flash TTS: A New Benchmark in Expressive and Controllable AI Voice Google DeepMind Releases Gemini Robotics-ER 1.6: Bringing Enhanced Embodied Reasoning and Instrument Reading to Physical AI Google Launches ‘Skills’ in Chrome: Turning Reusable AI Prompts into One-Click Browser Workflows TinyFish AI Releases Full Web Infrastructure Platform for AI Agents: Search, Fetch, Browser, and Agent Under One API Key NVIDIA and the University of Maryland Researchers Released Audio Flamingo Next (AF-Next): A Super Powerful and Open Large Audio-Language Model A Hands-On Coding Tutorial for Microsoft VibeVoice Covering Speaker-Aware ASR, Real-Time TTS, and Speech-to-Speech Pipelines Meta AI and KAUST Researchers Propose Neural Computers That Fold Computation, Memory, and I/O Into One Learned Model A Coding Implementation of MolmoAct for Depth-Aware Spatial Reasoning, Visual Trajectory Tracing, and Robotic Action Prediction MiniMax Just Open Sourced MiniMax M2.7: A Self-Evolving Agent Model that Scores 56.22% on SWE-Pro and 57.0% on Terminal Bench 2 Liquid AI Releases LFM2.5-VL-450M: a 450M-Parameter Vision-Language Model with Bounding Box Prediction, Multilingual Support, and Sub-250ms Edge Inference Researchers from MIT, NVIDIA, and Zhejiang University Propose TriAttention: A KV Cache Compression Method That Matches Full Attention at 2.5× Higher Throughput How to Build a Secure Local-First Agent Runtime with OpenClaw Gateway, Skills, and Controlled Tool Execution How Knowledge Distillation Compresses Ensemble Intelligence into a Single Deployable AI Model Alibaba’s Tongyi Lab Releases VimRAG: a Multimodal RAG Framework that Uses a Memory Graph to Navigate Massive Visual Contexts A Coding Guide to Markerless 3D Human Kinematics with Pose2Sim, RTMPose, and OpenSim NVIDIA Releases AITune: An Open-Source Inference Toolkit That Automatically Finds the Fastest Inference Backend for Any PyTorch Model Five AI Compute Architectures Every Engineer Should Know: CPUs, GPUs, TPUs, NPUs, and LPUs Compared An End-to-End Coding Guide to NVIDIA KVPress for Long-Context LLM Inference, KV Cache Compression, and Memory-Efficient Generation Meta Superintelligence Lab Releases Muse Spark: A Multimodal Reasoning Model With Thought Compression and Parallel Agents Sigmoid vs ReLU Activation Functions: The Inference Cost of Losing Geometric Context A Coding Guide to Build Advanced Document Intelligence Pipelines with Google LangExtract, OpenAI Models, Structured Extraction, and Interactive Visualization Google AI Research Introduces PaperOrchestra: A Multi-Agent Framework for Automated AI Research Paper Writing A Comprehensive Implementation Guide to ModelScope for Model Search, Inference, Fine-Tuning, Evaluation, and Export
A Coding Implementation of Crawl4AI for Web Crawling, Markdown Generation, JavaScript Execution, and LLM-Based Structured Extraction
2026-04-15 · via MarkTechPost

In this tutorial, we build a complete and practical Crawl4AI workflow and explore how modern web crawling goes far beyond simply downloading page HTML. We set up the full environment, configure browser behavior, and work through essential capabilities such as basic crawling, markdown generation, structured CSS-based extraction, JavaScript execution, session handling, screenshots, link analysis, concurrent crawling, and deep multi-page exploration. We also examine how Crawl4AI can be extended with LLM-based extraction to transform raw web content into structured, usable data. Throughout the tutorial, we focus on hands-on implementation to understand the major features of Crawl4AI v0.8.x and learn how to apply them to realistic data extraction and web automation tasks.

import subprocess
import sys


print("📦 Installing system dependencies...")
subprocess.run(['apt-get', 'update', '-qq'], capture_output=True)
subprocess.run(['apt-get', 'install', '-y', '-qq',
               'libnss3', 'libnspr4', 'libatk1.0-0', 'libatk-bridge2.0-0',
               'libcups2', 'libdrm2', 'libxkbcommon0', 'libxcomposite1',
               'libxdamage1', 'libxfixes3', 'libxrandr2', 'libgbm1',
               'libasound2', 'libpango-1.0-0', 'libcairo2'], capture_output=True)
print("✅ System dependencies installed!")


print("\n📦 Installing Python packages...")
subprocess.run([sys.executable, '-m', 'pip', 'install', '-U', 'crawl4ai', 'nest_asyncio', 'pydantic', '-q'])
print("✅ Python packages installed!")


print("\n📦 Installing Playwright browsers (this may take a minute)...")
subprocess.run([sys.executable, '-m', 'playwright', 'install', 'chromium'], capture_output=True)
subprocess.run([sys.executable, '-m', 'playwright', 'install-deps', 'chromium'], capture_output=True)
print("✅ Playwright browsers installed!")


import nest_asyncio
nest_asyncio.apply()


import asyncio
import json
from typing import List, Optional
from pydantic import BaseModel, Field


print("\n" + "="*60)
print("✅ INSTALLATION COMPLETE! Ready to crawl!")
print("="*60)


print("\n" + "="*60)
print("📖 PART 2: BASIC CRAWLING")
print("="*60)


from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode


async def basic_crawl():
   """The simplest possible crawl - fetch a webpage and get markdown."""
   print("\n🔍 Running basic crawl on example.com...")
  
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(url="https://example.com")
      
       print(f"\n✅ Crawl successful: {result.success}")
       print(f"📄 Title: {result.metadata.get('title', 'N/A')}")
       print(f"📝 Markdown length: {len(result.markdown.raw_markdown)} characters")
       print(f"\n--- First 500 chars of markdown ---")
       print(result.markdown.raw_markdown[:500])
      
   return result


result = asyncio.run(basic_crawl())


print("\n" + "="*60)
print("⚙️ PART 3: CONFIGURED CRAWLING")
print("="*60)


async def configured_crawl():
   """Crawling with custom browser and crawler configurations."""
   print("\n🔧 Running configured crawl with custom settings...")
  
   browser_config = BrowserConfig(
       headless=True,
       verbose=True,
       viewport_width=1920,
       viewport_height=1080,
       user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
   )
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       word_count_threshold=10,
       page_timeout=30000,
       wait_until="networkidle",
       verbose=True
   )
  
   async with AsyncWebCrawler(config=browser_config) as crawler:
       result = await crawler.arun(
           url="https://httpbin.org/html",
           config=run_config
       )
      
       print(f"\n✅ Success: {result.success}")
       print(f"📊 Status code: {result.status_code}")
       print(f"\n--- Content Preview ---")
       print(result.markdown.raw_markdown[:400])
      
   return result


result = asyncio.run(configured_crawl())


print("\n" + "="*60)
print("📝 PART 4: MARKDOWN GENERATION")
print("="*60)


from crawl4ai.content_filter_strategy import PruningContentFilter, BM25ContentFilter
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator


async def markdown_generation_demo():
   """Demonstrates raw vs fit markdown with content filtering."""
   print("\n🎯 Demonstrating markdown generation strategies...")
  
   browser_config = BrowserConfig(headless=True, verbose=False)
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       markdown_generator=DefaultMarkdownGenerator(
           content_filter=PruningContentFilter(
               threshold=0.4,
               threshold_type="fixed",
               min_word_threshold=20
           )
       )
   )
  
   async with AsyncWebCrawler(config=browser_config) as crawler:
       result = await crawler.arun(
           url="https://en.wikipedia.org/wiki/Web_scraping",
           config=run_config
       )
      
       raw_len = len(result.markdown.raw_markdown)
       fit_len = len(result.markdown.fit_markdown) if result.markdown.fit_markdown else 0
      
       print(f"\n📊 Markdown Comparison:")
       print(f"   Raw Markdown:  {raw_len:,} characters")
       print(f"   Fit Markdown:  {fit_len:,} characters")
       print(f"   Reduction:     {((raw_len - fit_len) / raw_len * 100):.1f}%")
      
       print(f"\n--- Fit Markdown Preview (first 600 chars) ---")
       print(result.markdown.fit_markdown[:600] if result.markdown.fit_markdown else "N/A")
      
   return result


result = asyncio.run(markdown_generation_demo())

We prepare the complete Google Colab environment required to run Crawl4AI smoothly, including system packages, Python dependencies, and the Playwright browser setup. We initialize the async-friendly notebook workflow with nest_asyncio, import the core libraries, and confirm that the environment is ready for crawling tasks. We then begin with foundational examples: a simple crawl, followed by a more configurable crawl that demonstrates how browser settings and runtime options affect page retrieval.

print("\n" + "="*60)
print("🔎 PART 5: BM25 QUERY-BASED FILTERING")
print("="*60)


async def bm25_filtering_demo():
   """Using BM25 algorithm to extract content relevant to a specific query."""
   print("\n🎯 Extracting content relevant to a specific query...")
  
   query = "legal aspects privacy data protection"
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       markdown_generator=DefaultMarkdownGenerator(
           content_filter=BM25ContentFilter(
               user_query=query,
               bm25_threshold=1.2
           )
       )
   )
  
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(
           url="https://en.wikipedia.org/wiki/Web_scraping",
           config=run_config
       )
      
       print(f"\n📝 Query: '{query}'")
       print(f"📊 Fit markdown length: {len(result.markdown.fit_markdown or '')} chars")
       print(f"\n--- Query-Relevant Content Preview ---")
       print(result.markdown.fit_markdown[:800] if result.markdown.fit_markdown else "No relevant content found")
      
   return result


result = asyncio.run(bm25_filtering_demo())


print("\n" + "="*60)
print("🏗️ PART 6: CSS-BASED EXTRACTION (No LLM)")
print("="*60)


from crawl4ai import JsonCssExtractionStrategy


async def css_extraction_demo():
   """Extract structured data using CSS selectors - fast and reliable."""
   print("\n🔧 Extracting data using CSS selectors...")
  
   schema = {
       "name": "Wikipedia Headings",
       "baseSelector": "div.mw-parser-output h2",
       "fields": [
           {
               "name": "heading_text",
               "selector": "span.mw-headline",
               "type": "text"
           },
           {
               "name": "heading_id",
               "selector": "span.mw-headline",
               "type": "attribute",
               "attribute": "id"
           }
       ]
   }
  
   extraction_strategy = JsonCssExtractionStrategy(schema, verbose=False)
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       extraction_strategy=extraction_strategy
   )
  
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(
           url="https://en.wikipedia.org/wiki/Python_(programming_language)",
           config=run_config
       )
      
       if result.extracted_content:
           data = json.loads(result.extracted_content)
           print(f"\n✅ Extracted {len(data)} section headings")
           print(f"\n--- Extracted Headings ---")
           for item in data[:10]:
               heading = item.get('heading_text', 'N/A')
               heading_id = item.get('heading_id', 'N/A')
               if heading:
                   print(f"  • {heading} (#{heading_id})")
       else:
           print("❌ No data extracted")
          
   return result


result = asyncio.run(css_extraction_demo())


print("\n" + "="*60)
print("🛒 PART 7: ADVANCED CSS EXTRACTION - Hacker News")
print("="*60)


async def advanced_css_extraction():
   """Extract stories from Hacker News with nested selectors."""
   print("\n🛍️ Extracting stories from Hacker News...")
  
   schema = {
       "name": "Hacker News Stories",
       "baseSelector": "tr.athing",
       "fields": [
           {
               "name": "rank",
               "selector": "span.rank",
               "type": "text"
           },
           {
               "name": "title",
               "selector": "span.titleline > a",
               "type": "text"
           },
           {
               "name": "url",
               "selector": "span.titleline > a",
               "type": "attribute",
               "attribute": "href"
           },
           {
               "name": "site",
               "selector": "span.sitestr",
               "type": "text"
           }
       ]
   }
  
   extraction_strategy = JsonCssExtractionStrategy(schema)
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       extraction_strategy=extraction_strategy
   )
  
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(
           url="https://news.ycombinator.com",
           config=run_config
       )
      
       if result.extracted_content:
           stories = json.loads(result.extracted_content)
           print(f"\n✅ Extracted {len(stories)} stories from Hacker News")
           print(f"\n--- Top 10 Stories ---")
           for story in stories[:10]:
               rank = story.get('rank', '?').strip('.') if story.get('rank') else '?'
               title = story.get('title', 'N/A')[:55]
               site = story.get('site', 'N/A')
               print(f"  #{rank:<3} {title:<55} ({site})")
              
   return result


result = asyncio.run(advanced_css_extraction())

We focus on improving the quality and relevance of extracted content by exploring markdown generation and query-aware filtering. We compare raw markdown with fit markdown to see how pruning reduces noise, and we use BM25-based filtering to keep only the parts of a page that align with a specific query. We then move into CSS-based extraction, where we define a structured schema and use selectors to pull clean heading data from a Wikipedia page without relying on an LLM.

print("\n" + "="*60)
print("⚡ PART 8: JAVASCRIPT EXECUTION")
print("="*60)


async def javascript_execution_demo():
   """Execute JavaScript on pages before extraction."""
   print("\n🎭 Executing JavaScript before crawling...")
  
   js_code = """
   // Scroll down to trigger lazy loading
   window.scrollTo(0, document.body.scrollHeight);
  
   // Wait for content to load
   await new Promise(r => setTimeout(r, 1000));
  
   // Scroll back up
   window.scrollTo(0, 0);
  
   // Add a marker to verify JS ran
   document.body.setAttribute('data-crawl4ai', 'executed');
   """
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       js_code=[js_code],
       wait_for="css:body",
       delay_before_return_html=1.0
   )
  
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(
           url="https://httpbin.org/html",
           config=run_config
       )
      
       print(f"\n✅ Page crawled with JS execution")
       print(f"📊 Status: {result.status_code}")
       print(f"📝 Content length: {len(result.markdown.raw_markdown)} chars")
      
   return result


result = asyncio.run(javascript_execution_demo())


print("\n" + "="*60)
print("🤖 PART 9: LLM-BASED EXTRACTION")
print("="*60)


from crawl4ai import LLMExtractionStrategy, LLMConfig


class Article(BaseModel):
   title: str = Field(description="The article title")
   summary: str = Field(description="A brief summary")
   topics: List[str] = Field(description="Main topics covered")


async def llm_extraction_demo():
   """Use LLM to intelligently extract and structure data."""
   print("\n🤖 LLM-based extraction setup...")
  
   import os
   api_key = os.getenv('OPENAI_API_KEY')
  
   if not api_key:
       print("\n⚠️ No OPENAI_API_KEY found. Showing setup code only.")
       print("\nTo enable LLM extraction, run:")
       print("   import os")
       print("   os.environ['OPENAI_API_KEY'] = 'sk-your-key-here'")
       print("\n--- Example Code ---")
       example_code = '''
from crawl4ai import LLMExtractionStrategy, LLMConfig
from pydantic import BaseModel, Field


class Product(BaseModel):
   name: str = Field(description="Product name")
   price: str = Field(description="Product price")


llm_strategy = LLMExtractionStrategy(
   llm_config=LLMConfig(
       provider="openai/gpt-4o-mini",  # or "ollama/llama3"
       api_token=os.getenv('OPENAI_API_KEY')
   ),
   schema=Product.model_json_schema(),
   extraction_type="schema",
   instruction="Extract all products with prices."
)


run_config = CrawlerRunConfig(
   extraction_strategy=llm_strategy,
   cache_mode=CacheMode.BYPASS
)


async with AsyncWebCrawler() as crawler:
   result = await crawler.arun(url="https://example.com", config=run_config)
   products = json.loads(result.extracted_content)
'''
       print(example_code)
       return None
  
   llm_strategy = LLMExtractionStrategy(
       llm_config=LLMConfig(
           provider="openai/gpt-4o-mini",
           api_token=api_key
       ),
       schema=Article.model_json_schema(),
       extraction_type="schema",
       instruction="Extract article titles and summaries."
   )
  
   run_config = CrawlerRunConfig(
       extraction_strategy=llm_strategy,
       cache_mode=CacheMode.BYPASS
   )
  
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(
           url="https://news.ycombinator.com",
           config=run_config
       )
      
       if result.extracted_content:
           data = json.loads(result.extracted_content)
           print(f"\n✅ LLM extracted:")
           print(json.dumps(data, indent=2)[:1000])
          
   return result


result = asyncio.run(llm_extraction_demo())

We continue structured extraction by applying nested CSS selectors to collect ranked story information from Hacker News in a clean JSON-like format. We then demonstrate JavaScript execution before extraction, which helps us interact with dynamic pages by scrolling, waiting for content, and modifying the DOM before processing. Finally, we introduce LLM-based extraction, define a schema with Pydantic, and show how Crawl4AI can convert unstructured web content into structured outputs using a language model.

print("\n" + "="*60)
print("🕸️ PART 10: DEEP CRAWLING")
print("="*60)


from crawl4ai.deep_crawling import BFSDeepCrawlStrategy
from crawl4ai.deep_crawling.filters import FilterChain, URLPatternFilter, DomainFilter


async def deep_crawl_demo():
   """Crawl multiple pages starting from a seed URL using BFS."""
   print("\n🕷️ Starting deep crawl with BFS strategy...")
  
   filter_chain = FilterChain([
       DomainFilter(
           allowed_domains=["docs.crawl4ai.com"],
           blocked_domains=[]
       ),
       URLPatternFilter(
           patterns=["*quickstart*", "*installation*", "*examples*"]
       )
   ])
  
   deep_crawl_strategy = BFSDeepCrawlStrategy(
       max_depth=2,
       max_pages=5,
       filter_chain=filter_chain,
       include_external=False
   )
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       deep_crawl_strategy=deep_crawl_strategy
   )
  
   pages_crawled = []
  
   async with AsyncWebCrawler() as crawler:
       results = await crawler.arun(
           url="https://docs.crawl4ai.com/",
           config=run_config
       )
      
       if isinstance(results, list):
           for result in results:
               pages_crawled.append(result.url)
               print(f"  ✅ Crawled: {result.url}")
               print(f"     📄 Content: {len(result.markdown.raw_markdown)} chars")
       else:
           pages_crawled.append(results.url)
           print(f"  ✅ Crawled: {results.url}")
           print(f"     📄 Content: {len(results.markdown.raw_markdown)} chars")
  
   print(f"\n📊 Total pages crawled: {len(pages_crawled)}")
   return pages_crawled


pages = asyncio.run(deep_crawl_demo())


print("\n" + "="*60)
print("🚀 PART 11: MULTI-URL CONCURRENT CRAWLING")
print("="*60)


async def multi_url_crawl():
   """Crawl multiple URLs concurrently for maximum efficiency."""
   print("\n⚡ Crawling multiple URLs concurrently...")
  
   urls = [
       "https://httpbin.org/html",
       "https://httpbin.org/robots.txt",
       "https://httpbin.org/json",
       "https://example.com",
       "https://httpbin.org/headers"
   ]
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       verbose=False
   )
  
   async with AsyncWebCrawler() as crawler:
       results = await crawler.arun_many(
           urls=urls,
           config=run_config
       )
      
       print(f"\n📊 Results Summary:")
       print(f"{'URL':<40} {'Status':<10} {'Content':<15}")
       print("-" * 65)
      
       for result in results:
           url_short = result.url[:38] + ".." if len(result.url) > 40 else result.url
           status = "✅" if result.success else "❌"
           content_len = f"{len(result.markdown.raw_markdown):,} chars" if result.success else "N/A"
           print(f"{url_short:<40} {status:<10} {content_len:<15}")
          
   return results


results = asyncio.run(multi_url_crawl())


print("\n" + "="*60)
print("📸 PART 12: SCREENSHOTS & MEDIA")
print("="*60)


async def screenshot_demo():
   """Capture screenshots and extract media from pages."""
   print("\n📷 Capturing screenshot and extracting media...")
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       screenshot=True,
       pdf=False,
   )
  
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(
           url="https://en.wikipedia.org/wiki/Web_scraping",
           config=run_config
       )
      
       print(f"\n✅ Crawl complete!")
       print(f"📸 Screenshot captured: {result.screenshot is not None}")
      
       if result.screenshot:
           print(f"   Screenshot size: {len(result.screenshot)} bytes (base64)")
          
       if result.media and 'images' in result.media:
           images = result.media['images']
           print(f"\n🖼️ Found {len(images)} images:")
           for img in images[:5]:
               print(f"   • {img.get('src', 'N/A')[:60]}...")
              
   return result


result = asyncio.run(screenshot_demo())

We expand from single-page crawling to deeper and broader workflows by introducing BFS-based deep crawling across multiple related pages. We configure a filter chain to control which domains and URL patterns are allowed, making the crawl targeted and efficient rather than uncontrolled. We also demonstrate concurrent multi-URL crawling and screenshot/media extraction, showing how Crawl4AI can scale across several pages while also collecting visual and embedded content.

print("\n" + "="*60)
print("🔗 PART 13: LINK EXTRACTION")
print("="*60)


async def link_extraction_demo():
   """Extract and analyze all links from a page."""
   print("\n🔗 Extracting and analyzing links...")
  
   run_config = CrawlerRunConfig(cache_mode=CacheMode.BYPASS)
  
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(
           url="https://docs.crawl4ai.com/",
           config=run_config
       )
      
       internal_links = result.links.get('internal', [])
       external_links = result.links.get('external', [])
      
       print(f"\n📊 Link Analysis:")
       print(f"   Internal links: {len(internal_links)}")
       print(f"   External links: {len(external_links)}")
      
       print(f"\n--- Sample Internal Links (first 5) ---")
       for link in internal_links[:5]:
           print(f"   • {link.get('href', 'N/A')[:60]}")
          
       print(f"\n--- Sample External Links (first 5) ---")
       for link in external_links[:5]:
           print(f"   • {link.get('href', 'N/A')[:60]}")
          
   return result


result = asyncio.run(link_extraction_demo())


print("\n" + "="*60)
print("🎯 PART 14: CONTENT SELECTION")
print("="*60)


async def content_selection_demo():
   """Target specific content using CSS selectors."""
   print("\n🎯 Targeting specific content with CSS selectors...")
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       css_selector="article, main, .content, #content, #mw-content-text",
       excluded_tags=["nav", "footer", "header", "aside"],
       remove_overlay_elements=True
   )
  
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(
           url="https://en.wikipedia.org/wiki/Web_scraping",
           config=run_config
       )
      
       print(f"\n✅ Content extracted with targeting")
       print(f"📝 Markdown length: {len(result.markdown.raw_markdown):,} chars")
       print(f"\n--- Preview (first 500 chars) ---")
       print(result.markdown.raw_markdown[:500])
      
   return result


result = asyncio.run(content_selection_demo())


print("\n" + "="*60)
print("🔐 PART 15: SESSION MANAGEMENT")
print("="*60)


async def session_management_demo():
   """Maintain browser sessions across multiple requests."""
   print("\n🔐 Demonstrating session management...")
  
   browser_config = BrowserConfig(headless=True)
  
   async with AsyncWebCrawler(config=browser_config) as crawler:
       session_id = "my_session"
      
       result1 = await crawler.arun(
           url="https://httpbin.org/cookies/set?session=demo123",
           config=CrawlerRunConfig(
               cache_mode=CacheMode.BYPASS,
               session_id=session_id
           )
       )
       print(f"  Step 1: Set cookies - Success: {result1.success}")
      
       result2 = await crawler.arun(
           url="https://httpbin.org/cookies",
           config=CrawlerRunConfig(
               cache_mode=CacheMode.BYPASS,
               session_id=session_id
           )
       )
       print(f"  Step 2: Read cookies - Success: {result2.success}")
       print(f"\n📝 Cookie Response:")
       print(result2.markdown.raw_markdown[:300])
      
   return result2


result = asyncio.run(session_management_demo())

We analyze the structure and navigability of a site by extracting both internal and external links from a page and summarizing them for inspection. We then demonstrate content targeting with CSS selectors and excluded tags, focusing extraction on the most meaningful sections of a page while avoiding navigation or layout noise. After that, we show session management, where we preserve browser state across requests and verify that cookies persist between sequential crawls.

print("\n" + "="*60)
print("🌟 PART 16: COMPLETE REAL-WORLD EXAMPLE")
print("="*60)


async def complete_example():
   """Complete example combining CSS extraction with content filtering."""
   print("\n🌟 Running complete example: Hacker News scraper with filtering")
  
   schema = {
       "name": "HN Stories",
       "baseSelector": "tr.athing",
       "fields": [
           {"name": "rank", "selector": "span.rank", "type": "text"},
           {"name": "title", "selector": "span.titleline > a", "type": "text"},
           {"name": "url", "selector": "span.titleline > a", "type": "attribute", "attribute": "href"},
           {"name": "site", "selector": "span.sitestr", "type": "text"}
       ]
   }
  
   browser_config = BrowserConfig(
       headless=True,
       viewport_width=1920,
       viewport_height=1080
   )
  
   run_config = CrawlerRunConfig(
       cache_mode=CacheMode.BYPASS,
       extraction_strategy=JsonCssExtractionStrategy(schema),
       markdown_generator=DefaultMarkdownGenerator(
           content_filter=PruningContentFilter(threshold=0.4)
       )
   )
  
   async with AsyncWebCrawler(config=browser_config) as crawler:
       result = await crawler.arun(
           url="https://news.ycombinator.com",
           config=run_config
       )
      
       if result.extracted_content:
           stories = json.loads(result.extracted_content)
          
           print(f"\n✅ Successfully extracted {len(stories)} stories!")
           print(f"\n{'='*70}")
           print("📰 TOP HACKER NEWS STORIES")
           print("="*70)
          
           for story in stories[:15]:
               rank = story.get('rank', '?').strip('.') if story.get('rank') else '?'
               title = story.get('title', 'No title')[:50]
               site = story.get('site', 'N/A')
               url = story.get('url', '')[:30]
               print(f"  #{rank:<3} {title:<50} ({site})")
              
           print("="*70)
          
           return stories
  
   return []


stories = asyncio.run(complete_example())


print("\n" + "="*60)
print("💾 BONUS: SAVING RESULTS")
print("="*60)


if stories:
   with open('hacker_news_stories.json', 'w') as f:
       json.dump(stories, f, indent=2)
   print(f"✅ Saved {len(stories)} stories to 'hacker_news_stories.json'")
   print("\nTo download in Colab:")
   print("   from google.colab import files")
   print("   files.download('hacker_news_stories.json')")


print("\n" + "="*60)
print("📚 TUTORIAL COMPLETE!")
print("="*60)


print("""
✅ What you learned:


1. Basic crawling with AsyncWebCrawler
2. Browser & crawler configuration
3. Markdown generation (raw vs fit)
4. BM25 query-based content filtering
5. CSS-based structured data extraction
6. Advanced CSS extraction (Hacker News)
7. JavaScript execution for dynamic content
8. LLM-based extraction setup
9. Deep crawling with BFS strategy
10. Multi-URL concurrent crawling
11. Screenshots & media extraction
12. Link extraction & analysis
13. Content targeting with CSS selectors
14. Session management
15. Complete real-world scraping example


📖 RESOURCES:
 • Docs: https://docs.crawl4ai.com/
 • GitHub: https://github.com/unclecode/crawl4ai
 • Discord: https://discord.gg/jP8KfhDhyN


🚀 Happy Crawling with Crawl4AI!
""")

We combine several ideas from the tutorial into a complete real-world example that extracts and filters Hacker News stories using structured CSS extraction and Markdown pruning. We format the results into a readable output, demonstrating how Crawl4AI can support a practical scraping workflow from collection to presentation. Finally, we save the extracted stories to a JSON file and close the tutorial with a clear summary of the major concepts and capabilities we have implemented throughout the notebook.

In conclusion, we developed a strong end-to-end understanding of how to use Crawl4AI for both simple and advanced crawling tasks. We moved from straightforward page extraction to more refined workflows involving content filtering, targeted element selection, structured data extraction, dynamic-page interaction, multi-URL concurrency, and deep crawling across linked pages. We also saw how the framework supports richer automation through media capture, persistent sessions, and optional LLM-powered schema extraction. As a result, we finished with a practical foundation for building reliable, efficient, and flexible scraping and crawling pipelines that are ready to support real-world research, monitoring, and intelligent data processing workflows.


Check out the Full Implementation Codes hereAlso, feel free to follow us on Twitter and don’t forget to join our 130k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us

Michal Sutter is a data science professional with a Master of Science in Data Science from the University of Padova. With a solid foundation in statistical analysis, machine learning, and data engineering, Michal excels at transforming complex datasets into actionable insights.