内容中心

2026年靠谱的智能触摸一体机热门厂家推荐汇总-深圳市朗欣电子有限公司

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

  1. Parse HTML: Use BeautifulSoup to parse the input HTML string, which handles malformed HTML gracefully.
  2. Collect URLs: Use a set to store URLs (auto-eliminates duplicates).
  3. Extract src: For each <img> tag, extract the src attribute (clean whitespace and add to set if non-empty).
  4. Extract srcset: Split the srcset attribute into entries (comma-separated), then extract the URL part (first element of each entry) and add to the set.
  5. 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 src and srcset attributes, 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 (add soup.find_all('source') and process their srcset attributes).

This script meets all the requirements and is suitable for real-world HTML parsing tasks.

深圳市朗欣电子有限公司

深圳市朗欣电子有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?