如何用Python解析SVG中polyline的points(支持URL与本地文件)
Got it, let's break down how to solve this problem efficiently. You need to pull SVG content (either from a URL or local file), extract all <polyline> elements, convert their points attribute into structured [[x,y], [x,y], ...] coordinate lists, and output each one individually.
Step 1: Install Required Libraries
We'll use BeautifulSoup for parsing the SVG/XML structure and requests to fetch content from URLs. Install them via pip:
pip install beautifulsoup4 requests
Step 2: Full Example Code
This script handles both URL and local SVG files, processes each <polyline>, and formats the points as requested:
from bs4 import BeautifulSoup import requests def parse_svg_polylines(source, is_url=True): # Get SVG content if is_url: response = requests.get(source) response.raise_for_status() # Raise error if request fails svg_content = response.text else: with open(source, 'r') as f: svg_content = f.read() # Parse SVG with BeautifulSoup soup = BeautifulSoup(svg_content, 'xml') polylines = soup.find_all('polyline') # Process each polyline's points for idx, polyline in enumerate(polylines, 1): points_attr = polyline.get('points', '') if not points_attr: print(f"Polyline {idx}: No points attribute found") continue # Convert points string to [[x,y], ...] format coordinate_pairs = [] for point_str in points_attr.split(): x_str, y_str = point_str.split(',') try: x = float(x_str) y = float(y_str) coordinate_pairs.append([x, y]) except ValueError: print(f"Polyline {idx}: Skipping invalid point '{point_str}'") print(f"Polyline {idx} coordinates:") print(coordinate_pairs) print("---") # Example usage with your provided SVG URL svg_url = "http://colorillo.com/bx0l.inline.svg" parse_svg_polylines(svg_url, is_url=True) # To use a local SVG file instead, uncomment this line: # parse_svg_polylines("path/to/your/file.svg", is_url=False)
How It Works
- Fetch/Read SVG Content: The function first retrieves SVG data—either via HTTP request for URLs or reading directly from a local file.
- Parse SVG:
BeautifulSoupparses the SVG as XML, making it easy to find all<polyline>elements. - Process Points: For each polyline:
- Extract the
pointsattribute value (a string like"239,274 239,274 ..."). - Split the string by spaces to get individual point strings.
- Split each point string by commas, convert to numeric values, and build the coordinate list.
- Output the formatted list, with error handling for invalid points.
- Extract the
Alternative: Using svgpathtools
If you need more advanced SVG manipulation later, consider the svgpathtools library. It's designed specifically for SVG path/polyline handling:
pip install svgpathtools
A quick snippet to extract polyline points:
from svgpathtools import svg2paths paths, attributes = svg2paths("http://colorillo.com/bx0l.inline.svg") for idx, attr in enumerate(attributes, 1): if 'points' in attr: points = attr['points'] # Same parsing logic as above to convert to [[x,y], ...] coordinate_pairs = [[float(coord) for coord in point.split(',')] for point in points.split()] print(f"Polyline {idx} coordinates:") print(coordinate_pairs) print("---")
This solution gives you exactly what you need: structured coordinate lists from every <polyline> in your SVG, whether it's hosted online or stored locally.
内容的提问来源于stack exchange,提问作者Ecks

