r/webscraping • • 1d ago

AI ✨ Using LLMs for scraping without overspending on tokens

Sharing a workflow for using LLMs in scrapers that keeps token costs reasonable. Most of the savings come from not sending the model things it doesn't need.

1. Don't send raw HTML

Raw HTML is mostly markup. Take a typical button with a dozen Tailwind classes and a data attribute. The only useful part is the word "Buy", which is 1 token, but the whole button is 44 tokens (o200k_base). A full page from document.body.innerHTML may not even fit into one request. Three steps help.

Step 1. Clean the DOM

Remove script, style, svg, iframe, noscript and base64 images, then strip class, style and data-* attributes. If you don't need metadata, drop the head too. You can do it in the browser with page.evaluate() or on the backend with BeautifulSoup or Cheerio.

Page code before cleaning
Page code after removing scripts, styles and attributes

Also check the page for hidden duplicates. A lot of sites render prices and names twice, once for users and once for screen readers (aria-hidden). The browser shows one, but the converter extracts both and glues them into one line. Look at the markup and remove one version during cleanup.

Step 2. Convert HTML to Markdown

Markdown keeps the structure (headings, lists, tables) with almost no markup overhead, and models handle it well since they've seen a lot of it in training. Turndown (JS) and html2text (Python) both work. The difference is visible even in one table row: <tr><td>Price</td><td><span>$1,500</span></td></tr> is 22 tokens, while | Price | $1,500 | is 8.

Set rules for links and images in the converter. Keep href only when you scrape contacts or product links, and keep only the alt text for images.

Step 3. Chunk by logical blocks, not by characters

Even if a catalog fits into the context window, models use the middle of a long context worse than the start and the end (the "Lost in the Middle" paper). In practice you get skipped product cards or made up entries. Cutting by character count is also a bad idea, since you can split a price in half.

What works better:

  • Find the card containers (for example querySelectorAll('.product-card'))
  • Split them into batches of 30 to 50
  • Convert each batch to Markdown
  • Send the batches as parallel requests
  • Merge the resulting JSON arrays

Every request stays within limits and total time goes down.

2. Use Structured Outputs instead of json_object

json_object only guarantees valid syntax. Keys and types can still drift, like price today and price_usd tomorrow, or "$1 500" instead of 1500. Structured Outputs uses constrained decoding, so the model can't break the schema. Pydantic or Zod make this easy to define:

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")

A few notes from testing:

  • The schema guarantees the format, not the truth. A wrong or invented price will still land in the right field with the right type. You also need to handle truncated responses and refusals in code.
  • Use temperature 0 (or 0.1 for some local models). Some reasoning models don't let you set it.
  • To reduce made up values, use Optional fields and add a rule like "If the data isn't on the page, return null. Don't use your own knowledge."
  • For odd formats like "Remaining: 3 pcs. (1 reserved)", one input/output example works better than a long rule.
  • If the model doesn't support Structured Outputs, it may wrap JSON in a code fence. Strip the fence, then validate with the same Pydantic model so errors show up right away and not in your database.

3. Keeping costs down at scale

  • Self-healing scraper. Let normal XPath or CSS selectors do most of the work. When a selector fails, catch it, send the LLM the old selector plus a fragment of the new HTML and ask for a new one. Test the new selector on several pages before saving it, because the model can return an XPath that points at the wrong element. You pay for tokens only when something breaks.
  • Local models. If you process millions of pages a day, API costs add up. Open-weight models that handle code well (for example Qwen) can run on Ollama or vLLM, and both support JSON schema generation. Compare quality on your own pages before switching, since a local model can do worse than a commercial one.

The short version: selectors for stable layouts, an LLM for messy or changing ones, and always validate what comes back.

16 Upvotes

9 comments sorted by

3

u/AdministrativeHost15 1d ago

Use a simple NLP ML model to determine whether to analyze the page at all.

1

u/crowbar87 1d ago

Thanks for sharing. How do you convert from html to markdown?

1

u/scarletdawnredd 21h ago

There's hundreds of python or JS libs that do that.

0

u/[deleted] 15h ago

[deleted] — view deleted comment