To extract an Open Graph preview image, read the final HTML response and collect the og:image declarations from its head in document order. Keep each image's own width, height, alt text, and alternate URL with that candidate. Then request the preferred image separately and check that the response decodes to a format and size your card can use. If the first candidate fails, record why before trying the next one. A useful preview record tells you which page declared the image, which asset you actually received, and why your card chose it.
Keep each image's attributes together
A page might declare a wide cover with both dimensions and then a square alternative with only a height. If you flatten the tags into one dictionary, the square image can inherit the cover's width. The card then reserves space for an image with the wrong aspect ratio.
The Open Graph protocol gives the first declaration preference when entries conflict and places structured properties after their root tag. Treat og:image:url as another spelling of the image declaration. Store og:image:secure_url as an alternate URL under the current image. Declared dimensions and MIME type are useful for debugging. Measure the downloaded file before using them to size a card.
The script below reads a saved HTML response and reports the ordered candidates and any image properties it cannot attach to a declaration. It reads direct meta children of the document head. Install beautifulsoup4, save the script as og_images.py, and pass it the HTML file. The script only inspects the saved file. Keep URL and access checks in a separate step before you fetch any candidate.
import json
import sys
from pathlib import Path
from bs4 import BeautifulSoup
def declared_images(html):
head = BeautifulSoup(html, "html.parser").head
tags = head.find_all("meta", recursive=False) if head else []
candidates, orphans = [], []
current = None
for tag in tags:
field = tag.get("property", "").strip().lower()
value = tag.get("content")
if field in {"og:image", "og:image:url"}:
current = {"property": field, "url": value, "declared": {}}
candidates.append(current)
elif field.startswith("og:image:"):
if current is None:
orphans.append({"property": field, "value": value})
else:
current["declared"].setdefault(field, []).append(value)
elif field.startswith("og:") and field.count(":") == 1:
current = None
return {"candidates": candidates, "orphan_properties": orphans}
if __name__ == "__main__":
html = Path(sys.argv[1]).read_bytes()
print(json.dumps(declared_images(html), indent=2))
Confirm that the image URL serves an image
Try the inventory on this public AnyCrawler article. Keep the status and effective URL with the saved response.
curl -fsSL --max-time 20 \
-w '%{http_code} %{url_effective}\n' \
https://anycrawler.com/blog/detect-soft-404s-before-web-extraction/ \
-o sample-page.html
python og_images.py sample-page.html
In this run, the page returned HTTP 200 and declared one image with no width or height tags. A separate request to the reviewed media URL returned HTTP 200 and image/webp. The downloaded file decoded as WebP at 1280 × 720 pixels. In a separate local test, the parser left the second image’s width unset when that declaration specified only a height.
For an approved candidate, inspect the asset response status, final URL, response media type, and decoded dimensions. Check the crop at the size you plan to display it. A redirect can lead to a legitimate CDN and still needs its own access check. When inspecting publisher markup on a site you control, prefer a complete HTTPS image URL so a consumer can request the candidate directly. For a third-party page with a relative value, preserve the value and treat any URL resolution as your application's compatibility choice.
| What you observe | What to record and show |
|---|---|
| First candidate decodes and fits the card | Record the declared and final image URLs, decoded dimensions, and selected declaration. |
| Image URL returns HTTP 200 with an HTML error page | Record the content type and failure. Test the next approved candidate or show a text-only card. |
| Image decodes but the declared dimensions differ | Use decoded dimensions for layout. Preserve both sets of values so the publisher can fix the declaration. |
| Several candidates decode | Start with the first suitable declaration. If your layout picks a later candidate, save that reason. |
| Page has no image declaration | Record the missing field. If your app uses a fallback, label it as such. |
If the image will support a claim in a research brief, continue with how to verify where an image came from. The tag tells you which picture the publisher associated with the page. Identifying the creator or establishing reuse rights calls for additional evidence.
Check page identity when the preview looks wrong
When the card artwork suggests you have the wrong article, inspect the page title and main text alongside the raw head. Paste the same URL into AnyCrawler's free URL-to-Markdown tool or use the documented single-page request.
curl -fsSG --max-time 30 \
--data-urlencode 'url=https://anycrawler.com/blog/detect-soft-404s-before-web-extraction/' \
https://api.anycrawler.com/free/v1/crawl -o free.json
The API request returned HTTP 200. The response also reported a target-page status of 200 and supplied a title, description, and Markdown. Its title and text matched the expected article. The response omitted a final URL and credit usage, so those fields stayed unset in this check. Use the direct HTML response for og:image order and attributes. Free results may be cached, so record when each response was observed if the page recently changed.
Search can find a page when you have only a query. Fetch serves reads of a known public URL when the material is in its HTML. Use Render to investigate a page whose content depends on JavaScript, and retain whether you inspected rendered output or the original response. Screenshot captures visible page state. If your test needs a click or a signed-in interaction, it belongs in a browser automation workflow with the appropriate access.
How long can your card show a previously verified image?
A card in a low-stakes reading list might keep the last known image through a temporary CDN error. A card in an alerts feed could conceal an editorial change if it shows the old image alongside a new headline. Storing the page observation and the image observation separately lets you explain which part of the card is stale and set an expiry appropriate to the surface.
A sharing service may have its own copy of either response. If yours looks correct and Facebook still shows the older preview, check Meta's sharing diagnostics to see what its crawler picked up. Decide what users of your own product should see while a new image is pending. For some cards the useful choice is the previous image with a recorded age. For others, a title with no thumbnail is clearer.
Frequently asked questions
Which image should I use if a page has more than one og:image?
Start with the first declaration in document order, then check that its image response decodes and fits the card. Keep the other declarations available for cases where the first fails or the artwork crops badly. If your card uses a later candidate, save the specific reason. That gives you a way to diagnose the result when the publisher or another preview consumer shows a different image.
What if the page declares a relative image URL?
Keep the declared value in the extraction record. When you control the page, replace it with a complete HTTPS image URL and verify that request independently. If your app chooses to resolve relative values on third-party pages, record the chosen base and resulting address as a compatibility decision. Include the effective page URL so a reviewer can inspect what happened after a redirect.
Why can an image URL return HTTP 200 and still fail?
The response can contain an HTML error page, a file your decoder cannot open, or an image too small for the intended card. Compare the response media type with the result of decoding the bytes. If a valid image arrives, measure it and check the actual crop. Preserve the failure reason before testing another candidate. That is more useful for debugging than a single blank image field.
Can I extract the same image tag from Markdown?
Use the returned HTML head for Open Graph tags and their order. A Markdown extraction aims to preserve readable page content and may omit the head entirely. You can use Markdown alongside the raw HTML to check that the response covers the article you expected. The free AnyCrawler example returned an article title and body, while the separate HTML inventory found the actual preview declaration.
Why does a sharing service still show an old image after the page changes?
Check the returned page and asset separately. The HTML may still declare the previous address, or the image host may still return earlier bytes at the same address. If both checks pass, review what the target service's own crawler saw using its diagnostics. Keep the observation times with the result so you can distinguish a publisher change, an asset change, and a preview that has yet to refresh.






