To solve this problem, we need to extract all unique image URLs from a given HTML string, handling both src and srcset attributes of <img> tags. The solution uses Python's BeautifulSoup library for robust HTML parsing and set data structure to ensure uniqueness.
Step-by-Step Explanation
- Parse HTML: Use BeautifulSoup to parse the input HTML string, which handles malformed HTML gracefully.
- Collect URLs: Use a set to store URLs (auto-eliminates duplicates).
- Extract
src: For each<img>tag, extract thesrcattribute (clean whitespace and add to set if non-empty). - Extract
srcset: Split thesrcsetattribute into entries (comma-separated), then extract the URL part (first element of each entry) and add to the set. - Output: Convert the set to a list for easy access and output.
Python Script
First, install the required library:
pip install beautifulsoup4
from bs4 import BeautifulSoup
def extract_image_urls(html_content):
"""Extract unique image URLs from an HTML string."""
soup = BeautifulSoup(html_content, 'html.parser')
image_urls = set() # Use set to avoid duplicates
for img in soup.find_all('img'):
# Handle src attribute
src = img.get('src')
if src:
cleaned_src = src.strip()
if cleaned_src:
image_urls.add(cleaned_src)
# Handle srcset attribute
srcset = img.get('srcset')
if srcset:
entries = srcset.split(',')
for entry in entries:
parts = entry.strip().split()
if parts:
url = parts[0].strip()
if url:
image_urls.add(url)
return list(image_urls)
# Example Usage
if __name__ == "__main__":
sample_html = """
<html>
<body>
<img src="image1.jpg" alt="Image1">
<img src="image2.png" srcset="image2-2x.png 2x, image2-hd.png 100w" alt="Image2">
<img srcset="image3.webp 1x, image3-4k.webp 2x" alt="Image3">
<img src=" image4.gif " alt="Whitespace">
<img src="" alt="Empty">
</body>
</html>
"""
urls = extract_image_urls(sample_html)
print("Unique Image URLs:")
for url in urls:
print(url)
Key Features
- Uniqueness: Uses sets to ensure no duplicate URLs.
- Robustness: Handles
srcandsrcsetattributes, whitespace, and empty values. - Efficiency: Set operations are O(1) average time, making the script fast even for large HTML strings.
- Portability: Uses BeautifulSoup's built-in
html.parser(no external dependencies beyond bs4).
Example Output
For the sample HTML, the output will be:
image1.jpg, image2.png, image2-2x.png, image2-hd.png, image3.webp, image3-4k.webp, image4.gif.
Notes
- Relative URLs: To convert relative URLs to absolute, use
urllib.parse.urljoin(base_url, relative_url). - Picture Tags: For
<picture>elements, extend the script to handle<source>tags (addsoup.find_all('source')and process theirsrcsetattributes).
This script meets all the requirements and is suitable for real-world HTML parsing tasks.


作者声明:本文包含人工智能生成内容。