Google SERP API Raw HTML: Retrieve and Validate rawUrl
Senior Web Scraping Engineer
TL;DR:
- metadata.rawUrl points to stored Google SERP HTML. Fetch that URL after the completed JSON response arrives.
- HTML retrieval is a second HTTP request. The search response does not embed that downloaded document in the field itself.
- Document checks provide evidence with limits. Status, media type, byte count, and structure help detect problems but do not prove every feature is complete.
- Keep the original bytes and a checksum. A local copy remains inspectable independently of a remote storage link's availability.
Introduction: Keep a Page Behind the Parsed Result
Structured search data is convenient for analysis, but a JSON field alone cannot show everything about the page from which it was extracted. A stored HTML document gives you another inspection surface when a result needs explanation.
Scrapeless Google Search API can return metadata.rawUrl alongside structured results. This Google SERP API raw HTML tutorial retrieves that document and checks what was downloaded. The goal is an auditable local artifact, not a claim that saved markup reproduces every interaction of a live browser page.
The Google Search quickstart response shows the field under metadata. The broader actor request model supplies the search data first; the HTML download comes afterward.
What rawUrl Represents
The rawUrl value is a URL for a stored page document associated with the response. It is not the final destination URL of an organic search result.
Keep three addresses conceptually separate: the API endpoint that accepted the search, the stored SERP HTML address, and a result link that may lead to a publisher's page. Downloading the SERP document does not retrieve every linked article, product, or business page.
Do not build a storage path from the query or a task ID. Read the exact URL from the completed response. The storage location is an output value, and a copied address from a documentation example is not evidence for your own request.
A missing rawUrl should become an explicit “HTML unavailable” state in your workflow. It should not be replaced with a newly constructed Google search URL, because that would initiate a different observation.
Retrieve JSON Before Downloading HTML
The search task must be complete before the HTML-fetching program reads its metadata. If the search returns HTTP 201, use the task result workflow to obtain the completed object first.
The script below expects that object saved as serp.json. Its other prerequisites are Python and Requests, installed with python -m pip install requests. Save it as fetch_serp_html.py and run python fetch_serp_html.py beside the saved response.
The observed storage URL uses HTTPS on api.scrapeless.com under /storage/. The program limits downloads to that observed host and path shape, follows no redirects, and sends no API-key header to storage. A future change to the storage host should trigger review of the rule instead of an unrestricted fetch.
URL checks need to examine components rather than substrings. The URI syntax specification defines the scheme, authority, path, and other components used by that check.
python
import hashlib
import json
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import urlsplit
import requests
class DocumentShape(HTMLParser):
def __init__(self):
super().__init__()
self.opened = set()
self.closed = set()
def handle_starttag(self, tag, attrs):
self.opened.add(tag)
def handle_endtag(self, tag):
self.closed.add(tag)
data = json.loads(Path("serp.json").read_text(encoding="utf-8"))
metadata = data.get("metadata")
raw_url = metadata.get("rawUrl") if isinstance(metadata, dict) else None
if not isinstance(raw_url, str) or not raw_url:
raise ValueError("metadata.rawUrl is absent")
parts = urlsplit(raw_url)
if (parts.scheme != "https" or parts.hostname != "api.scrapeless.com"
or parts.port not in (None, 443) or parts.username or parts.password
or not parts.path.startswith("/storage/")):
raise ValueError("Storage URL needs review before downloading")
# The storage fetch uses no API-key header and follows no redirects.
with requests.get(raw_url, timeout=(10, 60), stream=True, allow_redirects=False) as response:
response.raise_for_status()
if response.status_code != 200:
raise ValueError(f"Unexpected storage status: {response.status_code}")
media_type = response.headers.get("Content-Type", "").split(";")[0].lower()
if media_type not in ("text/html", "application/xhtml+xml"):
raise ValueError(f"Unexpected media type: {media_type}")
chunks = []
size = 0
for chunk in response.iter_content(65536):
size += len(chunk)
if size > 10 * 1024 * 1024:
raise ValueError("HTML exceeds this example's local size limit")
chunks.append(chunk)
html_bytes = b"".join(chunks)
if not html_bytes:
raise ValueError("Empty HTML body")
Path("serp.html").write_bytes(html_bytes)
shape = DocumentShape()
shape.feed(html_bytes.decode("utf-8", errors="replace"))
report = {
"bytes": len(html_bytes),
"sha256": hashlib.sha256(html_bytes).hexdigest(),
"has_html": "html" in shape.opened,
"has_body": "body" in shape.opened,
"has_closing_html": "html" in shape.closed,
"source_url": raw_url,
}
Path("serp-html-check.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
print(json.dumps({key: value for key, value in report.items() if key != "source_url"}))
The local ten-mebibyte limit is an example client safeguard, not the API's maximum HTML size. A larger document is a reason to review your expected workload and adjust the local policy deliberately. The program writes the bytes only after a successful bounded download.
Start Scraping with Scrapeless
Power up your web scraping and automation workflow with Scrapeless!
Sign up today and get $5 in free credit — no credit card required.Claim your free credit now in the Scrapeless Dashboard.
Check the Download at Several Levels
A useful HTML check records transport success, document type, payload size, structure, and correspondence with the original search. No single check proves all of them.
The baseline coffee response used for this tutorial led to a second request with HTTP 200 and Content-Type: text/html. The download contained 1,938,204 bytes and included opening html and body elements plus a closing html element. These are observations from one stored document, not minimum-size requirements for later responses.
| Check | What It Establishes | What It Does Not Establish |
|---|---|---|
| HTTP status | The storage request completed as expected | The document contains the intended results |
| Media type | The server identified the representation as HTML | Every search feature is present |
| Nonempty bytes | A body was downloaded | The body is the right page |
| Document elements | Basic markup structure exists | Semantic completeness or rendering fidelity |
| Checksum | Later bytes can be compared with the saved copy | Authenticity of every statement on the page |
| Query and result inspection | The document corresponds to selected response details | Completeness of all possible search modules |
The meaning of response headers and content representations is defined by HTTP representation semantics. Treat a content-type check as one signal, not a substitute for reading the document.
Python's HTMLParser interface recognizes markup events. It is not a browser renderer or a complete conformance validator. The boolean structure fields in the report therefore remain modest checks.
Inspect Whether the HTML Matches the Search
Correspondence checks should compare the stored document with the request and selected returned records. Begin with the query shown on the page and a small sample of titles or links that are present in the JSON.
Text may be entity-encoded, split across elements, or represented differently in embedded data. A raw substring miss is a reason to inspect the document, not immediate proof that a result is absent. If you render the file locally, external assets and scripts may be unavailable or may request current resources, so rendering can differ from the original retrieval.
Use the saved document to answer a specific question. For example, determine whether a title appears in the markup, whether an unexpected link form is present, or whether the document is actually a search page. Avoid upgrading these observations into a claim that every dynamic expansion or hidden module was captured.
Troubleshoot Missing or Unusable HTML
An HTML issue should be classified at the step where it occurs. Keep the completed search JSON even when the storage fetch fails.
| Symptom | Check |
|---|---|
metadata is absent |
Confirm you saved the completed search object |
rawUrl is missing or empty |
Record HTML as unavailable for that response |
| URL rejected by the script | Compare the actual storage origin with the approved origin |
| Non-200 storage response | Retain status and request context; do not label it a document |
| Unexpected media type | Inspect the response before treating it as HTML |
| Size limit reached | Review the local limit and expected document size |
| Structure checks fail | Inspect the bytes; valid parsing alone is insufficient |
| Query or result mismatch | Compare the saved JSON and HTML from the same request |
Do not assume a permanent retention period for a remote storage address. Download the document while it is available if your process needs an archive. Store the JSON, HTML, checksum, and collection context together so that another engineer can understand the relationship.
Conclusion: Preserve What Was Actually Downloaded
The raw HTML workflow has two distinct operations: retrieve completed search JSON, then download its stored HTML URL. Save the document and record checks that say precisely what was observed.
Use the Google Search API parameters to control the original query, and consult current pricing when planning the search workload. Keep HTML availability separate from organic-result availability in your own reporting.
Build Your Search Data Workflow
Join developers working with search data in our community: Discord · Telegram.
Create a Scrapeless account and apply this tutorial to a small query set before scheduling a larger collection.
FAQ
Q: Does rawUrl contain the HTML text?
No. It contains a URL. A second HTTP request downloads the document.
Q: Is rawUrl an organic result's final destination?
No. It points to the stored SERP document associated with the response, not to every website listed on that SERP.
Q: Does a closing html tag prove the whole SERP is complete?
No. It is a structural signal. Content correspondence and dynamic-feature completeness require additional inspection.
Q: Should the storage request include the API key?
The observed storage download succeeded without the authentication header. This example keeps the key confined to the API request and does not forward it to storage or result websites.
Q: Is a stored HTML link a permanent archive?
Do not assume a retention guarantee that has not been established. Keep a local copy and checksum when the document is needed later.
Q: Can saved HTML replace destination-page verification?
No. SERP HTML records the search page. Verification of a linked page's content is a separate task.
At Scrapeless, we only access publicly available data while strictly complying with applicable laws, regulations, and website privacy policies. The content in this blog is for demonstration purposes only and does not involve any illegal or infringing activities. We make no guarantees and disclaim all liability for the use of information from this blog or third-party links. Before engaging in any scraping activities, consult your legal advisor and review the target website's terms of service or obtain the necessary permissions.



