Extract SVG from a Website in Python

SVG content can be embedded directly in an HTML document as an <svg> element or loaded from an external .svg file. These cases require different extraction workflows: serialize inline markup or download the referenced resource.

To extract SVG from a website in Python, load the page with HTMLDocument. Find inline <svg> elements and save their outer_html, or locate external .svg URLs, resolve them against document.base_uri, and download the files through the document network service.

Extract Inline SVG from a Website

An inline SVG is an <svg> element whose markup is part of the HTML DOM rather than a separate file. The example selects every <svg> element and writes its complete serialized markup to a numbered UTF-8 file such as 0.svg or 1.svg.

To extract inline SVG markup:

  1. Create the output/svg directory and load the web page into an HTMLDocument.
  2. Call get_elements_by_tag_name(“svg”) to collect inline SVG elements.
  3. Enumerate the elements to generate a distinct numeric file name for each one.
  4. Write each element’s outer_html to a UTF-8 .svg file.
 1# Extract inline SVG from a website in Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Prepare the output directory
 7output_dir = os.path.join("output", "svg")
 8os.makedirs(output_dir, exist_ok=True)
 9
10# Load the webpage and save each inline SVG
11with ah.HTMLDocument("https://docs.aspose.com/svg/tutorial/svg-shapes/") as document:
12    # Collect all inline SVG images
13    images = document.get_elements_by_tag_name("svg")
14
15    for i, image in enumerate(images):
16        with open(os.path.join(output_dir, f"{i}.svg"), "w", encoding="utf-8") as file:
17            file.write(image.outer_html)

Extract and reuse SVG content only when permitted by the website terms, applicable licenses, and copyright law.

Download External SVG Files from HTML

An external SVG is stored separately and referenced by a URL. The second example inspects <img src> values, keeps distinct strings ending in .svg, resolves relative references, and downloads successful responses.

To download externally referenced SVG files:

  1. Load the web page and collect all <img> elements.
  2. Read distinct src values and keep those ending in .svg.
  3. Resolve each relative reference against document.base_uri with Url.
  4. Create a RequestMessage and send it through document.context.network.
  5. If the response is successful, derive the file name from the URL path and write the returned bytes to output/svg.
 1# Download SVG images from a website in Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.net as ahnet
 6
 7# Prepare the output directory
 8output_dir = os.path.join("output", "svg")
 9os.makedirs(output_dir, exist_ok=True)
10
11# Load the webpage and collect external SVG URLs
12with ah.HTMLDocument("https://products.aspose.com/html/python-net/") as document:
13    images = document.get_elements_by_tag_name("img")
14    image_urls = {image.get_attribute("src") for image in images if image.get_attribute("src")}
15
16    # Download each external SVG image
17    for image_url in image_urls:
18        url = ah.Url(image_url, document.base_uri)
19
20        if not url.pathname.lower().endswith(".svg"):
21            continue
22
23        with ahnet.RequestMessage(url) as request:
24            with document.context.network.send(request) as response:
25                if response.is_success:
26                    file_path = os.path.join(output_dir, os.path.basename(url.pathname))
27                    with open(file_path, "wb") as file:
28                        file.write(response.content.read_as_byte_array())

Inline vs. External SVG Extraction

SVG sourceExtraction method
Inline <svg>...</svg>Select the <svg> element and save its outer_html.
<img src="image.svg">Resolve src, request the external resource, and save the response bytes.
<object data="image.svg"> or <embed src="image.svg">Not covered by these examples; inspect the corresponding data or src attribute.
CSS background-image or SVG referenced from a stylesheetNot covered; inspect CSS resource URLs separately.
SVG <use href="sprites.svg#symbol">Requires processing the referenced SVG file and fragment identifier separately.

Common SVG Extraction Issues

IssueCause and recommended action
No inline SVG files are createdThe loaded DOM contains no <svg> elements. Inspect the page source or loaded DOM before saving.
An external SVG URL is missedThe code only accepts strings ending exactly in .svg. A query string, uppercase extension, or another referencing element requires additional URL parsing.
An output file has an empty nameThe external URL has no file name in its path. Assign an explicit local name.
One SVG overwrites anotherDifferent URLs can share the same basename. Generate unique output names when collisions are possible.
A saved response is not SVGThe request returned an error document or another media type. Validate the response and content type before saving.
Extracted inline SVG looks differentIts appearance depends on external CSS, fonts, images, or inherited page styles that are not included in outer_html. Preserve or recreate those dependencies when needed.

FAQ

What is the difference between inline and external SVG?

Inline SVG markup is part of the HTML DOM and can be serialized directly. An external SVG is a separate resource identified by a URL and must be downloaded.

Does the code extract every SVG used by a website?

No. The examples cover inline <svg> elements and .svg files referenced by <img src>. SVG used through CSS, <object>, <embed>, <use>, scripts, or URLs with nonstandard forms requires additional handling.

Why can an extracted inline SVG lose its styling?

outer_html preserves the SVG element and its descendants, but it does not automatically copy external stylesheets, fonts, images, or styles inherited from the surrounding HTML document.

Other Platforms

Related Articles