Short answer: when a web scrape API returns empty content from a JavaScript-rendered property page, keep the cheap HTTP fetch as the default, detect whether the response contains the listing fields you require, and retry only that failed document through a browser-capable worker. Store the normalized listing and its evidence, not every rendered page forever. For retrieval-augmented search, replace chunks by stable listing ID and source revision so stale rent or availability cannot outrank a fresh record.
Start with the bill, because the wrong workaround multiplies it. For 100,000 listing checks per day, a pipeline that renders every URL performs 100,000 browser jobs; if an evidence-based gate finds that 8,000 responses lack required fields, the browser tier performs 8,000. Those figures are an illustrative capacity model, not a benchmark or vendor price. The dominant term is rendered executions, followed by retained HTML and screenshots, so selective escalation changes the term that matters while preserving deterministic handling for ordinary server-rendered pages.
The deliberate retention boundary is equally important. Keep the extracted fields, content hash, observation time, source URL, fetch mode, and enough evidence to audit a disputed change. Expire raw bodies and screenshots under a documented schedule unless legal or reconciliation requirements say otherwise. The cost is real: after expiry, an engineer can prove what the extractor recorded but may no longer be able to reconstruct every pixel or transient script response that produced it.
What should you do when a web scrape API returns empty content?
An HTTP 200 status establishes that a response was delivered; it does not establish that a rent, address, or availability value exists in the returned representation. A page may ship an HTML shell and populate the useful nodes after scripts run. It may also embed useful state in a script element even when visible text is sparse. Consent flows, authentication, regional variants, and bot controls are separate cases, and a browser is not permission to bypass them. Respect the site's terms, access controls, and robots policy; RFC 9309 defines the Robots Exclusion Protocol, but it does not grant authorization to content.
Treat “empty” as a schema result rather than len(body) == 0. For a rental-comp feed, the minimum useful record might require a stable source ID, canonical URL, observed timestamp, and at least one decision field such as asking rent or availability. Navigation text is not success. A 40 KB shell can be semantically empty, while a compact embedded JSON object can be sufficient.
The following classifier is intentionally conservative. It neither guesses a selector nor declares success from raw byte count; it records why the document needs escalation, which makes retries idempotent and reviewable.
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
"time"
)
type FetchResult struct {
URL string
Status int
Body []byte
ObservedAt time.Time
FetchMode string
}
type GateDecision struct {
NeedsRender bool
Reason string
BodyHash string
}
func classify(r FetchResult) GateDecision {
sum := sha256.Sum256(r.Body)
d := GateDecision{BodyHash: hex.EncodeToString(sum[:])}
if r.Status < 200 || r.Status >= 300 {
d.NeedsRender = false
d.Reason = fmt.Sprintf("http_status_%d", r.Status)
return d
}
body := strings.ToLower(string(r.Body))
hasIdentity := strings.Contains(body, "listing-id") || strings.Contains(body, "property-id")
hasDecisionField := strings.Contains(body, "asking-rent") || strings.Contains(body, "availability")
if !hasIdentity || !hasDecisionField {
d.NeedsRender = true
d.Reason = "required_listing_fields_absent"
return d
}
d.Reason = "required_listing_fields_present"
return d
}
Replace those marker checks with a real HTML parser and site-specific extraction contract. A successful fetch must satisfy business fields, provenance fields, and validation rules. Logging only “empty page” discards the distinction between a transport failure, a valid delisting, a selector drift, and a client-rendered shell.
Empty is a verdict.
Escalate once, then make the write idempotent
Use three outcomes after the first fetch: accept, render, or quarantine. A non-2xx response should follow an explicit retry policy rather than being silently converted into a browser request. A 2xx document missing the required schema can enter the rendering queue. A rendered document that still lacks the schema belongs in quarantine with its reason and evidence metadata; repeated rendering will not manufacture a trustworthy rent.
Short retries matter.
Give each observation a deterministic key such as source + listing ID + source revision, or use a body hash when the source supplies no revision. The browser worker may deliver twice after a timeout, so the database write must converge on one observation. This is the same discipline used around financial postings: delivery can repeat, while the durable effect remains singular and auditable.
package ingest
import (
"context"
"database/sql"
"time"
)
type Observation struct {
Key string
ListingID string
URL string
ContentHash string
FetchMode string
ObservedAt time.Time
AskingRent int64
Currency string
}
func Store(ctx context.Context, db *sql.DB, o Observation) error {
const q = `
INSERT INTO listing_observations
(observation_key, listing_id, source_url, content_hash,
fetch_mode, observed_at, asking_rent_minor, currency)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(observation_key) DO NOTHING`
_, err := db.ExecContext(ctx, q, o.Key, o.ListingID, o.URL,
o.ContentHash, o.FetchMode, o.ObservedAt, o.AskingRent, o.Currency)
return err
}
The SQL placeholder syntax and conflict clause vary by database, so adapt the statement to the driver in use. The invariant does not vary: acknowledge the job only after the observation and its audit metadata commit together. Do not claim end-to-end exactly-once delivery when the crawler, queue, and database cannot provide it; enforce exactly-once effect at the write boundary instead.
A browser worker should wait for a contract-relevant condition, such as a listing container becoming available, within a bounded deadline. “Network idle” alone is a weak business signal because analytics, ads, or live connections can keep traffic active. Conversely, sleeping for an arbitrary number of seconds hides both fast success and permanent failure. Capture the final URL as well, since redirects can reveal a delisted or login state.
This fallback has limits. It is not suitable when the operator lacks permission to retrieve the page, when the required data sits behind authentication that the workflow is not authorized to use, or when the source offers a licensed structured feed whose contract already supplies the required fields. In those cases, do not attempt a more elaborate browser disguise: stop collection, obtain authorization, or ingest the permitted feed. Selective rendering also trades operational simplicity for fidelity, because browser binaries, script execution, deadlines, and resource isolation create a larger failure surface than plain HTTP; that trade-off is justified only for sources whose required fields appear after authorized client-side execution.
Chunk around decisions, not DOM layout
Once extraction works, chunking becomes the primary relevance control. A property manager comparing nearby rentals asks questions such as “two-bedroom units available this month within this district,” so one giant page chunk mixes amenities, legal boilerplate, navigation, and pricing. Tiny chunks split the address from the rent and make the retrieved evidence ambiguous.
Create one identity chunk for stable facts, one current-offer chunk for rent and availability, and optional amenity or policy chunks when those fields are populated. Every chunk should carry listing_id, observed_at, source_revision, and chunk_kind. Preserve currency and rent period as structured fields instead of asking an embedding to infer whether 2400 is monthly rent, a deposit, or square footage.
| Chunk kind | Include | Replace when | Retrieval use |
|---|---|---|---|
| Identity | address, unit type, bedrooms | identity fields change | entity match and deduplication |
| Current offer | asking rent, currency, period, availability | any offer field or source revision changes | price and availability ranking |
| Amenities | normalized amenity facts | amenity set changes | preference matching |
RAG combines retrieval with generation, but generation does not repair stale or missing evidence. The original RAG paper describes generation conditioned on retrieved external memory; operationally, that makes the quality and version of the retrieved record part of the answer contract. If two current-offer chunks for one listing remain searchable without an explicit history query, the system can cite yesterday's rent with perfect linguistic fluency.
Use replacement semantics for the live index and retain history in a separate audit store. This gives the reranker one current candidate per listing while preserving a trace for reconciliation. It also limits index growth: an unchanged observation updates last_seen_at without creating another embedding.
Freshness belongs in the ranking contract
Freshness should not be a vague boost applied after relevance. Define eligibility first. A listing whose availability observation exceeds the business-defined maximum age can be excluded from “available now” answers, while the same record may remain eligible for a historical rent analysis. The maximum age is a product and compliance decision; there is no universal correct number.
Then rerank eligible candidates with explicit, inspectable features. Semantic similarity can express query fit, while source revision, observation age, field completeness, and geographic precision constrain whether a match is dependable. Keep the arithmetic versioned. A score change can alter which property appears first, and an audit trail should identify the feature values and rule version used for that decision.
package ranking
import "time"
type Candidate struct {
Similarity float64
Completeness float64
ObservedAt time.Time
}
func Eligible(c Candidate, now time.Time, maxAge time.Duration) bool {
return !c.ObservedAt.After(now) && now.Sub(c.ObservedAt) <= maxAge
}
func Score(c Candidate, now time.Time, maxAge time.Duration) float64 {
if !Eligible(c, now, maxAge) {
return -1
}
freshness := 1 - now.Sub(c.ObservedAt).Seconds()/maxAge.Seconds()
return 0.70*c.Similarity + 0.20*freshness + 0.10*c.Completeness
}
The weights are an example policy, not measured truth. Validate them against labeled property-search questions, record the policy version, and include cases where an older semantically close listing must lose to a current exact-area match. Clock skew deserves a test too; the example rejects observations from the future rather than awarding them extra freshness.
No score can restore absent evidence.
Operate the fallback as a controlled expense
Deploy the HTTP and rendering paths as separate worker pools so a surge in shell pages cannot consume every ordinary fetch slot. Bound queue age, attempts, and per-origin concurrency. Emit counts for initial schema pass, render escalation, rendered schema pass, quarantine reason, duplicate observation, and indexing lag. Those measures explain both spend and correctness without storing sensitive page content in logs.
Before enabling a new extractor, replay a fixed corpus of permitted fixtures through both paths. Include a server-rendered listing, a JavaScript shell, a delisted page, a consent page, malformed embedded state, a duplicate delivery, and a rent change with the same listing ID. Follow one failure all the way through: the initial 200 response lacks rent, the gate records required_listing_fields_absent, one render job produces the fields, a repeated delivery hits the same observation key, the index replaces the previous current-offer chunk, and a retrieval test confirms that the new rent wins while the old observation remains available only to the audit query. Then reverse one condition at a time. If rendered output still lacks rent, it must enter quarantine rather than overwrite the last valid offer; if the observation timestamp is in the future, it must be ineligible; if the parser version changes without a content change, the audit event must still identify which parser produced the record. The acceptance test is not merely “text is non-empty.” It is that normalized fields, evidence hash, freshness behavior, and idempotent database effect match the contract across retries and partial failures.
Roll out by source and watch the escalation ratio. A sharp change can indicate a site redesign, consent variant, or extraction regression, but the metric alone cannot identify which one. Sample quarantined evidence under access controls, update the parser, and reprocess by content hash so the repair is reproducible.
Finally, document deletion. Raw browser artifacts may contain personal data or session material, so minimize collection, restrict access, and apply the retention policy chosen with legal and security reviewers. Keep durable audit events compact: observation key, timestamps, hashes, parser version, ranking-policy version, and outcome. When raw evidence expires, record that deletion as an event rather than leaving an unexplained hole.
The practical workaround is selective rendering backed by a field-level success contract. Its value is larger than recovering text: it prevents empty shells from entering retrieval, keeps current rental offers distinct from history, and gives each reranked result a traceable chain from fetch to decision. Stop retaining artifacts that no longer serve that chain, while accepting that expired evidence limits later forensic reconstruction.
Further reading
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks: https://arxiv.org/abs/2005.11401
- RFC 9309, Robots Exclusion Protocol: https://www.rfc-editor.org/rfc/rfc9309
- WHATWG HTML Living Standard, scripting: https://html.spec.whatwg.org/multipage/scripting.html
- W3C Data on the Web Best Practices, data versioning and provenance: https://www.w3.org/TR/dwbp/
Top comments (0)