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

推荐订阅源

WordPress大学
WordPress大学
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Project Zero
Project Zero
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
P
Proofpoint News Feed
量子位
K
Kaspersky official blog
S
SegmentFault 最新的问题
博客园 - 叶小钗
博客园 - 司徒正美
酷 壳 – CoolShell
酷 壳 – CoolShell
Hugging Face - Blog
Hugging Face - Blog
博客园 - Franky
F
Fortinet All Blogs
Scott Helme
Scott Helme
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cisco Blogs
T
Tenable Blog
U
Unit 42
S
Schneier on Security
T
The Blog of Author Tim Ferriss
G
Google Developers Blog
C
Cybersecurity and Infrastructure Security Agency CISA
V
Visual Studio Blog
The Hacker News
The Hacker News
Jina AI
Jina AI
Stack Overflow Blog
Stack Overflow Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
I
Intezer
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
V
Vulnerabilities – Threatpost
L
LINUX DO - 热门话题
Spread Privacy
Spread Privacy
T
The Exploit Database - CXSecurity.com
V
V2EX
Help Net Security
Help Net Security
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
大猫的无限游戏
大猫的无限游戏
www.infosecurity-magazine.com
www.infosecurity-magazine.com
PCI Perspectives
PCI Perspectives
腾讯CDC
Webroot Blog
Webroot Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
News | PayPal Newsroom
Recorded Future
Recorded Future
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
C
Check Point Blog

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
How I Sniffed Xiaohongshu's Collection API in 90 Seconds — and Why CORS Made Me Rewrite the Whole Approach
孫昊 · 2026-04-29 · via DEV Community

TL;DR

I needed to pull a user's saved-posts list from Xiaohongshu (China's Instagram-meets-Pinterest) for offline analysis. Their web client renders the data, but their API has a request-signature scheme that defeats casual scraping. After three failed approaches — Playwright sniff, manual cookie injection, direct API fetch — the working solution turned out to be the inverse of "automate the API call": let the browser issue the request and listen for the response. 250 saved posts in 90 seconds. Here's what each approach taught me.

This is part 2 of a series. Part 1 covered shipping four iOS apps with one Claude Code agent; this part is one of the agent's harder side-quests.

The setup

I'm building an offline AI-prompt manager for iOS. I needed evidence that "AI-related content" was a real user interest signal, not just a guess. The cheapest evidence: my own saved-posts history on Bilibili and Xiaohongshu. Bilibili had a clean public API — 347 items pulled in 30 seconds. Xiaohongshu? Different story.

Stack used throughout:

  • Python 3.12
  • Playwright 1.50 with Chromium
  • macOS / Windows compatible (subprocess.run + pathlib)
  • Storage state persisted as JSON for re-entry without re-login

Attempt 1 — login + cookie polling

The standard Playwright pattern: launch a headed browser, let the user log in interactively, watch for a "logged-in" cookie to appear, save the storage state.

# login_and_save.py — first version
def has_login_cookie(context, name: str) -> bool:
    cookies = context.cookies()
    return any(c.get("name") == name and c.get("value") for c in cookies)

# Polling loop
while time.time() < deadline:
    if has_login_cookie(context, "web_session"):  # XHS sets this on login
        context.storage_state(path=str(state_path))
        browser.close()
        return 0
    time.sleep(2)

Enter fullscreen mode Exit fullscreen mode

I ran the script. It happily reported "登录成功! storage state saved" within 5 seconds — even though I hadn't actually scanned the QR code yet. The cookie was set, but…

# Probe: am I really logged in?
resp = page.request.get("https://edith.xiaohongshu.com/api/sns/web/v2/user/me")
data = resp.json()
print(data["data"]["guest"])  # → True

Enter fullscreen mode Exit fullscreen mode

Lesson 1: Xiaohongshu sets the web_session cookie immediately on first page load — for guest users too. The cookie is not a login signal. It's a session ID that gets associated with a user only after authentication.

The fix: poll for guest: false from the actual /me endpoint, not for cookie presence.

def _xhs_logged_in(page, context) -> bool:
    try:
        resp = page.request.get(
            "https://edith.xiaohongshu.com/api/sns/web/v2/user/me",
            headers={"Accept": "application/json"},
        )
        return resp.json().get("data", {}).get("guest", True) is False
    except Exception:
        return False

Enter fullscreen mode Exit fullscreen mode

This works. After a real login, guest: false flips. Storage state saves cleanly.

Attempt 2 — direct API fetch

Now logged in. Time to find the collection endpoint.

I started with educated guesses based on naming conventions seen on similar Chinese apps:

candidates = [
    "https://edith.xiaohongshu.com/api/sns/web/v1/note/collect_page?num=20&cursor=",
    "https://edith.xiaohongshu.com/api/sns/web/v2/note/collect_page?num=20&cursor=",
    "https://edith.xiaohongshu.com/api/sns/web/v1/user_posted/collected?num=20",
    "https://edith.xiaohongshu.com/api/sns/web/v1/user/collected?num=20",
]

Enter fullscreen mode Exit fullscreen mode

Every single one returned 404 page not found. Not 401, not 403 — a flat 404. Either the endpoints had been renamed, or my guesses were wrong on a fundamental dimension.

Lesson 2: When you guess endpoints and get 404 across all variants, stop guessing. Sniff what the browser actually does.

Attempt 3 — Playwright network sniff

I added page.on("request") and page.on("response") listeners and navigated to the user's profile in a headed browser. Then I let myself click around manually and watched what the browser fetched.

def on_request(req):
    url = req.url
    if "xiaohongshu.com/api/" in url or "edith.xiaohongshu" in url:
        captured.append({
            "method": req.method,
            "url": url,
            "headers": dict(req.headers),
        })

Enter fullscreen mode Exit fullscreen mode

90 seconds of clicking and scrolling produced 41 captured API calls. The interesting one:

GET https://edith.xiaohongshu.com/api/sns/web/v2/note/collect/page
?num=30
&cursor=
&user_id=...
&image_formats=jpg,webp,avif
&xsec_token=
&xsec_source=

Enter fullscreen mode Exit fullscreen mode

So the path is note/collect/page (singular note, slash-separated collect/page) — not note/collect_page, not user_posted/collected. None of my guesses had been close.

I copied that URL into a direct script invocation:

url = "https://edith.xiaohongshu.com/api/sns/web/v2/note/collect/page?num=30&cursor=&user_id=...&image_formats=jpg,webp,avif&xsec_token=&xsec_source="
resp = page.request.get(url, headers={"Accept": "application/json", "Origin": "...", "Referer": "..."})
print(resp.json())
# → {"code": -1, "success": false}

Enter fullscreen mode Exit fullscreen mode

Lesson 3: A request that the browser issues successfully will not necessarily work when you replay it directly — even with the same cookies. The server is checking something else.

What broke: x-s signature headers

Xiaohongshu uses a request-signature scheme. Every API call from the official web client includes three headers:

  • x-s (a hash signature)
  • x-s-common (a "platform fingerprint" payload)
  • x-t (a timestamp)

These are computed by the front-end JavaScript before each fetch. The implementation lives in heavily-obfuscated bundle code that runs in the browser and signs each request based on the URL, body, and a per-session secret.

To reproduce these signatures from Python you'd need to either reverse-engineer the obfuscated signing code (hours; brittle to bundle updates) or run a JS engine alongside Python (overhead; jsdom doesn't quite work because the real bundle expects browser APIs).

Both options are bad-ROI for a one-shot offline analysis.

Lesson 4: When the platform makes API replay expensive, don't replay. Borrow the browser's signing for free.

The fix: let the browser issue the request, listen for the response

The signed-request problem disappears if you don't issue the request from your code at all. Instead:

  1. Have Playwright drive the page to load whatever data you want (clicking the right tab, scrolling)
  2. Let the front-end JS sign and issue the calls itself
  3. Listen to the HTTP responses with page.on("response") and capture the JSON bodies
pages_data: list[dict] = []
last_response_time = [time.time()]

def on_response(resp):
    if "/api/sns/web/v2/note/collect/page" in resp.url and resp.status == 200:
        body = resp.json()
        pages_data.append(body)
        last_response_time[0] = time.time()

page.on("response", on_response)

# Navigate + click collection tab + scroll loop
page.goto(f"https://www.xiaohongshu.com/user/profile/{user_id}")
page.locator("[class*='reds-tab']:has-text('收藏')").first.click()
time.sleep(3)

for _ in range(60):  # cap
    page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
    time.sleep(1.2)
    if time.time() - last_response_time[0] > 8:  # idle = done
        break

Enter fullscreen mode Exit fullscreen mode

Each scroll triggers another collect/page request from the front end. The front end signs it correctly. The server returns paginated JSON. My listener captures the body.

250 saved posts in 25 paginated responses, ~90 seconds end-to-end.

The full output is structured cleanly:

{
  "data": {
    "notes": [
      {
        "note_id": "...",
        "type": "video",
        "title": "ai直接把我公寓租出去了 把我家具也卖了",
        "user": {"nickname": "L"},
        "interact_info": {"liked_count": "8650"}
      }
    ],
    "cursor": "...",
    "has_more": true
  }
}

Enter fullscreen mode Exit fullscreen mode

What this enabled

With 250 collected posts in JSON, I ran simple keyword-based classification (regex against ~15 tightened patterns covering LLM/Chat, Image-Gen, Video-Gen, Coding-Agent, Agent/Automation, Voice/Music, RAG/Embedding, General-AI):

  • 36 of 250 were AI-related (14.4%)
  • Top signal: 21 posts about LLM/Chat (Claude Code being the dominant brand — 11 posts mentioned it directly)
  • Second: Coding-Agent (Cursor / Aider / Continue) — 11 posts (notably 0 in my Bilibili sample, suggesting Xiaohongshu is where the user's "newer" interest pattern shows up)

These signals fed directly into product decisions for the iOS prompt-manager app I'm shipping. The "Claude Code starter prompts" section of the bundled prompt library got expanded from 0 to 7 items — driven by behavior data, not guess.

Generalized lessons for any "scrape from a hostile API" problem

  1. A cookie isn't necessarily login state. Test with an actual identity-API call.
  2. 404 across multiple endpoint guesses = stop guessing. Sniff the browser instead.
  3. API replay fails on signed requests. That's the platform's threat model talking.
  4. Don't fight the signature scheme. Outsource it to the browser. Drive the page, listen to responses.
  5. Idle detection > fixed scroll count. Loop until N seconds without new responses, not until N scrolls.
  6. Keep the user out of the polling loop. A working "did the user log in" detector should poll an authoritative API, not a side-effect cookie.

Cost analysis

Approach Engineer hours Reliability
Reverse-engineer x-s signatures 4-8 hrs Brittle to bundle updates
jsdom + bundle replay 6-12 hrs Memory-heavy, fragile
Playwright + response listener (this post) 30 minutes Works as long as the UI tab works

The browser-as-signer approach is also more honest: you're using the same code path the site expects you to use. You just happen to keep the data around.

Code

The full set of scripts (login, sniff, collected, analyze) lives in the AutoApp toolkit repo. License is MIT.

If you adapt the response-listener pattern to other Chinese platforms (Douyin / Zhihu / Jike), I'd love to hear what works.