大語言模型如何用於網頁爬取並控制 token 成本
How to Use LLMs for Web Scraping Without Overspending on Tokens
以大語言模型輔助網頁爬取,可先清理 HTML、轉成 Markdown 並按邏輯分批,再用 JSON schema 減少 token 用量並固定輸出格式。JSON schema 只約束回應格式,不保證抽取值正確,因此仍要以程式驗證資料和新生成的選擇器。大規模處理時,可讓傳統選擇器處理穩定頁面,只在失效時調用模型;亦可評估自託管開放權重模型,並按自有頁面比較抽取質素。
A scraper that worked for months stops returning prices after a site redesign: the CSS classes were regenerated, the XPath expressions match nothing, and the regular expressions have grown too complicated to maintain. An LLM finds data by meaning rather than by position in the markup, so layout changes matter much less to it. Knowing how to use LLMs for web scraping, though, also means knowing what they cost. Sending a whole page to a model burns tokens on markup, and the extracted data still needs verification.
This article covers how to prepare HTML so that it uses fewer tokens, how to get a response in a fixed JSON format, and how to keep the cost down at scale by using the model only where a traditional scraper fails.
How to prepare HTML before sending it to an LLM
The preparation is three steps: clean the DOM, convert the result to Markdown and split it into chunks. This lowers token usage and makes it easier for the model to find the data.
The HTML has to be retrieved first. For many sites a regular script is enough. If a site blocks automated requests, the options include browser profiles with separate fingerprints and proxies, which Octo Browser provides. Its API can launch a profile and connect Playwright to it, as described in Automating Octo Browser using API.
Raw HTML is mostly markup. A typical button looks like this:
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mt-4 w-full flex items-center justify-center" data-id="12345">Buy</button>
The only useful data in it is the word "Buy", which is a single token. The whole button takes 44 tokens with the o200k_base tokenizer used by GPT-4o models. Sending this code to an API means paying to process CSS classes, and it also distracts the model from the actual data. A complete page, such as document.body.innerHTML, may not fit into the token limit of a single request at all.
Step 1. Clean up the DOM
Remove everything that carries no useful information: the <script>, <style>, <svg>, <iframe> and <noscript> tags, and base64-encoded images. This can be done in the browser with page.evaluate() or on the backend with BeautifulSoup or Cheerio. After that, drop the class, style and data-* attributes. If the page metadata is not needed, the contents of <head> can go too: stylesheet links, meta tags and comments.
HTML page code before cleaning
Page code after removing scripts, styles and attributes
This is also the moment to look for duplicates. Many sites output prices and product names twice: one copy is visible to users and the other is hidden for screen readers. The browser shows only one of them, but a converter extracts both and merges them into one line. Remove one version during cleanup, for example elements with the aria-hidden="true" attribute. Which version to keep depends on the site's markup, so inspect the page's code before configuring the cleanup.
Step 2. Convert HTML to Markdown
Markdown keeps the structure of HTML (headings, lists, tables) with almost no markup overhead. LLMs were trained on data from GitHub, Reddit and Wikipedia, where Markdown is common, so they handle it well. Turndown (JavaScript) and html2text (Python) can do the conversion.
The difference is visible even in one table row. In HTML, <tr><td>Price</td><td><span>$1,500</span></td></tr> takes 22 tokens, while the Markdown row | Price | $1,500 | takes 8.
The converter also needs rules for links and images. Keep the href attribute only when scraping contact details or product-page links, and drop it otherwise. For images, keep just the text from the alt attribute. The less markup remains in the text, the less noise competes with the data.
Converted page text with duplicated prices from hidden elements
Step 3. Split the content into chunks
Even when a catalog fits into the context window, sending it in one piece is not ideal. In machine learning this is known as the Lost in the Middle effect: research has shown that LLMs use information from the middle of a long context less effectively than information at its start or end. With a large catalog, the model can skip some product cards in the middle of the list or invent entries that are not there.
Splitting by character count, for example markdown_text.substring(0, 5000), is a poor fix: the cut can land in the middle of a word or a price. A better way is to split into logical blocks while processing the DOM:
- The script finds all product-card containers, for example with
document.querySelectorAll('.product-card'). - The array of cards is divided into batches, for example 30 to 50 cards per batch.
- Each batch is converted to Markdown separately.
- The batches go to the LLM in parallel requests. The number of concurrent requests depends on the API limits.
- The script merges the resulting JSON arrays into one.
This way the model processes each short fragment completely, every request stays within the token limit, and parallel requests shorten the total processing time.
How to get JSON from an LLM with a predefined schema
The Structured Outputs mode generates JSON that follows a predefined schema: the field names and data types in the response match the schema exactly. This is often called strict JSON.
The older json_object mode guarantees only valid syntax, meaning the brackets and quotes are in the right places. Field names and types can still drift. Today the model may return a price key and tomorrow price_usd, or the string "$1 500" instead of the number 1500. A script that expects price to be a number fails on such a response.
Structured Outputs relies on constrained decoding. At each generation step the API checks the possible next tokens against the JSON schema and discards any that would break it. If the schema requires a number, the model cannot put letters into that field. Schemas are convenient to define with Pydantic in Python or Zod in JavaScript.
A quick test shows the effect. The system prompt below demands the price in words, while the schema requires a number:
import os
from pydantic import BaseModel
from openai import OpenAI
# Read the API key from an environment variable instead of hardcoding it
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Schema: price must be a number (float)
class Product(BaseModel):
title: str
price: float
# Adversarial prompt: ask for the price in words
html_chunk = "Name: Gaming laptop. Price: one hundred thousand rubles."
evil_prompt = "RETURN THE PRICE IN WORDS ONLY! No digits! This is critical!"
# Structured Outputs request: the .parse method with the schema in response_format
response = client.chat.completions.parse(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": evil_prompt},
{"role": "user", "content": html_chunk},
],
response_format=Product,
temperature=0.0,
)
result = response.choices[0].message.parsed
print("\n=== RESULT ===")
print(result)
print(f"Data type of the price field: {type(result.price)}")
The schema guarantees the format of the response, not the accuracy of the values. If the model makes a mistake or invents a price, the value still arrives in the right field and type. The schema also does not protect against responses cut off by token limits or against the model refusing to answer, so the code has to handle those cases.
Every schema field can carry a description, which the model takes into account when filling it in:
from typing import Optional
from pydantic import BaseModel, Field
class Product(BaseModel):
title: str = Field(description="Full product name without SEO filler")
price: Optional[float] = Field(description="Price as a number only. If there is a discount, use the final price")
in_stock: Optional[bool] = Field(description="Whether the product is in stock")
For data extraction, set temperature to 0, or to 0.1 for some local models. The model then picks the most likely tokens, so responses to the same HTML come out almost identical. APIs do not guarantee full reproducibility, though, and some reasoning models do not allow setting temperature at all.
An LLM generates text by predicting the most likely continuation. If a smartphone's battery capacity appears in almost every spec in its training data, the model may add one even when the page says nothing about it. Two techniques reduce this risk:
- Use optional fields in the schema, such as
Optional[float]in the example above. - Add a
nullrule to the system prompt, for example: "If the data isn't on the page, return null. Don't make up values or use your own knowledge. Extract only what is present in the provided text."
For unusual formats, one or two input and output examples in the prompt help. A site might say "Remaining: 3 pcs. (1 reserved)", leaving it unclear which number to use. A single example with the expected answer works better than a long rule.
Models without Structured Outputs support, including some local models and alternative APIs, may wrap JSON in a Markdown code block:
```json
{ "price": 1500 }
```
json.loads() and JSON.parse() fail on such a response. The fix is to strip the fences before parsing and then validate the result with the same Pydantic model:
import re
# Strip Markdown code fences, then validate against the schema
clean_response = re.sub(r"```(?:json)?\s*", "", raw_response).strip()
product = Product.model_validate_json(clean_response)
This way a formatting error shows up immediately instead of in the database. The more precisely the schema and the prompt are defined, the less room the model has for interpretation and the more predictable the result.
How to use LLMs for web scraping at scale without overspending
At large volumes it is cheaper to use the LLM as support for a traditional scraper than to push every page through the model. The other lever is running the model on your own server.
Self-healing scraper
XPath and CSS selectors should do most of the work, and the LLM steps in only when the scraper breaks:
- The script scrapes pages with traditional selectors.
- The site changes its layout, the selector no longer finds the price, and a
try/exceptblock catches the error. - The script sends the LLM the old selector and a fragment of the new HTML with a request like: "Here's the old XPath and a fragment of the new DOM. Return a new XPath for the price."
- The script tests the new selector on several pages. If it works, the selector is saved to the configuration and scraping resumes.
Tokens are spent only when something breaks, not on every page. The validation in step 4 should not be skipped, because the model may return an XPath that matches the wrong element.
Local models
OpenAI or Anthropic APIs are convenient for prototyping, but processing millions of pages a day, for example when monitoring marketplaces, can make API costs substantial. One alternative is an open-weight model on your own server or a rented GPU server. Models that perform well on code, such as Qwen, suit scraping tasks. They can be run with Ollama or vLLM, and both support generation against JSON schemas, so the approach from the previous section works here as well.
The costs are then limited to server rental or electricity, and the data does not go to third-party services. Before switching, compare extraction quality on your own pages, because a local model may perform worse than a commercial one.
Conclusion
An LLM complements traditional scraping rather than replacing it. XPath and CSS selectors handle stable layouts faster and more cheaply, and a model earns its cost when the data is scattered through text or the layout changes constantly. To keep the approach predictable, strip markup and hidden duplicates from the HTML, convert it to Markdown and split it into logical batches. Request responses against a JSON schema, and validate both the extracted data and any newly generated selectors in code.
來源:DEV Community · dev.to


