Web Content Structuring and Refactoring: A Practical Guide
This guide explains how to turn web pages into structured markup as an engineering problem rather than a one-off script. It covers secure access token handling, request layer design with rate limiting and retries, fault-tolerant layered parsing, incremental deduplication with content fingerprints, result validation metrics, and a cloud integration approach, helping you build a stable and maintainable content pipeline for knowledge bases and AI applications.
1. Background and Refactoring Goals
In scenarios such as capturing enterprise knowledge, archiving technical documentation, and preparing corpora for intelligent question answering, a large amount of valuable information still exists in the form of web pages. This type of content has distinct characteristics: its structure is driven by the presentation layer, tags are deeply nested, styles and data are mixed together, and pagination and lazy loading are common. Copying and pasting directly loses hierarchy information, while scraping scripts that rely on a single fixed selector break easily whenever the page is redesigned.
Therefore, the process of “web content to structured markup” should be refactored as an engineering problem rather than written as a one-off script. The core goals of the refactoring can be summarized in four points:
- Stability: when the page structure changes, the parsing logic can degrade gracefully instead of collapsing entirely;
- Maintainability: collection, parsing, conversion, and validation are decoupled into layers that can be replaced independently;
- Security: identity credentials are not written to disk, not written to logs, and not hard-coded;
- Verifiability: conversion results have clear completeness metrics and can be regression tested.
2. Obtaining Access Credentials Correctly and Security Boundaries
Content APIs on many sites require a login state to access. They typically issue an access token, and subsequent requests carry this token in the header to complete identity verification. The general approach is as follows: after logging in through the browser, open the developer tools network panel, filter for API requests, and check the authentication field in the request headers.
The security boundary needs to be emphasized, as this part is often overlooked:
- A token is equivalent to a temporary key for the account, and leaking it is equivalent to the account being impersonated for a short time;
- It should not be written into source code, committed to a version repository, pasted into public channels, or shared externally via screenshots;
- It should be stored only in local environment variables or a key management service, and actively invalidated after the task is complete;
- When abnormal call records are found, log out immediately to invalidate the token and reissue a new one.
An illustrative local configuration approach (only expressing the idea, without pointing to any specific product):
# Inject via environment variables to avoid appearing in command-line history and codeexport CONTENT_ACCESS_TOKEN="<your-token>"
import osheaders = {"Authorization": f"Bearer {os.environ['CONTENT_ACCESS_TOKEN']}","Accept": "application/json",}
3. Request Layer Design: From “It Runs” to “It Is Controllable”
The request layer is not about sending a single request, but about sending the right requests stably over the long term. The following elements are worth focusing on:
- Concurrency and rate limiting: use a token bucket to control requests per second to avoid triggering risk controls; set a minimum interval for requests to the same domain;
- Retry strategy: retry only on timeouts, connection interruptions, 5xx, and 429, using exponential backoff with random jitter;
- Timeout splitting: set connection timeout and read timeout separately to prevent threads from hanging for a long time;
- Session reuse: reuse the same session connection pool to reduce handshake overhead;
- Context pass-through: pass session identifiers, page cursors, and so on as explicit parameters to avoid implicit global state.
import time, random, requestsfrom requests.adapters import HTTPAdaptersession = requests.Session()session.mount("https://", HTTPAdapter(pool_connections=8, pool_maxsize=8))def fetch(url, headers, params=None, max_retry=3):for attempt in range(max_retry):try:resp = session.get(url, headers=headers, params=params, timeout=(5, 20))if resp.status_code == 429 or resp.status_code >= 500:raise RuntimeError(f"retryable status {resp.status_code}")resp.raise_for_status()return respexcept Exception:if attempt == max_retry - 1:raisetime.sleep((2 ** attempt) + random.random())
4. Parsing Layer: Fault-Tolerant Layered Extraction
The parsing layer is the part that yields the greatest benefit from refactoring. A “three-layer degradation” structure is recommended:
- Structured data first: if the response is in a structured data format, map directly by fields for the highest fidelity;
- Semantic tag fallback: when structured data is missing, extract by semantic tags such as headings, paragraphs, lists, code blocks, and tables;
- Text stream fallback: when both previous layers fail, degrade to plain text extraction, mark it with low confidence, and send it to a manual review queue.
Key implementation points:
- Use “content density” rather than fixed class names to locate the main content, removing navigation, sidebars, and recommendation slots;
- Preserve hierarchy: map headings to different levels, keep ordered/unordered attributes for lists, and retain language annotations for code blocks;
- Handle lazy loading: trigger loading only for content in the visible area to avoid fetching irrelevant resources;
- Unified cleaning: remove duplicate whitespace, fix truncated entities, and merge sentences broken across paragraphs.
def to_markdown(node, depth=0):tag = node.nameif tag in ("h1", "h2", "h3", "h4"):return "#" * int(tag[1]) + " " + node.get_text(strip=True) + "\n"if tag == "pre":return "```\n" + node.get_text() + "\n```\n"if tag == "li":return " " * depth + "- " + node.get_text(strip=True) + "\n"if tag == "p":return node.get_text(strip=True) + "\n\n"return "".join(to_markdown(c, depth + 1) for c in node.children)
5. Incremental Updates, Deduplication, and Result Validation
A one-time full crawl is not advisable in real environments. A more robust approach is to introduce a content fingerprint: compute a digest value after normalizing the main content and use it as a unique key to determine whether it has already been processed; at the same time, record the source address and update time to achieve incremental updates and the idempotent semantics of “rewrite only when content changes.”
The validation step should cover at least four metrics:
- Completeness rate: the ratio of the number of extracted main-content characters to the visible main content on the page;
- Structural fidelity rate: the consistency of the number of headings, lists, and code blocks with the source page;
- Garbled rate: the proportion of abnormal characters and replacement characters;
- Traceable failures: each record retains the source address, crawl time, and confidence, making it easy to locate problem samples.
When the completeness rate falls below the threshold, automatically switch to fallback parsing and raise an alert, rather than silently producing incomplete content.
6. A General Approach to Connecting with Cloud Capabilities
As the collection scale grows, each stage can be mapped to general cloud product categories: raw snapshots are stored in object storage to retain traceable copies; parsing tasks are decoupled and peak-shaved through a message queue; batch conversion runs on a container platform for elastic scaling; and runtime logs and metrics are connected to logging services and monitoring alerts to make failure rates, latency, and completeness observable. Baidu AI Cloud provides the above general category capabilities, which can be combined as needed to form a closed loop of “collection, parsing, validation, and archiving.”
7. Common Issues and Troubleshooting Checklist
- Authentication failure returned: confirm the token has not expired and the request header field name and format are correct;
- Empty main content returned: mostly caused by dynamic rendering; trigger loading or switch to the structured data channel;
- Content truncation: check the read timeout and whether the pagination cursor is advancing;
- Frequent rate limiting: reduce concurrency, increase intervals, and reuse sessions;
- Result drift: pin the parsing version and retain a regression sample set; run regression tests before going live after changes.
8. Conclusion
Doing web-to-structured-markup conversion well is essentially about converging uncertainty into a controllable range: credential management holds the security baseline, layered parsing handles structural changes, and fingerprints and validation ensure trustworthy results. With this refactoring, what was originally a fragile script evolves into sustainable content infrastructure, providing a high-quality corpus foundation for knowledge bases and intelligent applications.
