Extract Image Sources by CSS Class

  • Share this:

Code introduction


This function accepts HTML content and a CSS class name as parameters, uses the PyQuery library to find all img elements with the specified class name, and returns a list of their src attributes.


Technology Stack : PyQuery

Code Type : Function

Code Difficulty : Intermediate


                
                    
def find_images_with_class(html, class_name):
    from pyquery import PyQuery as pq

    # Initialize PyQuery object with the given HTML content
    doc = pq(html)

    # Find all elements with the specified class name and extract their 'src' attribute
    images = doc(f'.{class_name} img').map(lambda img: pq(img).attr('src'))

    # Return the list of image URLs
    return list(images)                
              
Tags: