Last modified: Oct 29, 2023 By Alexander Williams

Working with <meta> Tags using BeautifulSoup [Examples]

Example 1: Find All <meta> Tags in an HTML Document


from bs4 import BeautifulSoup

html = """
<html>
    <head>
        <meta name="description" content="A sample page">
        <meta charset="UTF-8">
        <meta name="author" content="John Doe">
    </head>
    <body>
        <p>Some content</p>
    </body>
</html>
"""

# Create a BeautifulSoup object to parse the HTML
soup = BeautifulSoup(html, 'html.parser')

# Find all <meta> tags within the HTML
meta_tags = soup.find_all('meta')

# Print the attributes of each <meta> tag
for meta in meta_tags:
    print(meta.attrs)

Output:


{'name': 'description', 'content': 'A sample page'}
{'charset': 'UTF-8'}
{'name': 'author', 'content': 'John Doe'}
    

Example 2: Find a Specific <meta> Tag by Name


# Find a specific <meta> tag by its name attribute
description_meta = soup.find('meta', attrs={"name": "description"})

# Print the attributes of the matched <meta> tag
print(description_meta.attrs)

Output:


{'name': 'description', 'content': 'A sample page'}
    

Example 3: Find <meta> Tags with Specific Attributes


# Find <meta> tags with a specific name attribute
author_meta_tags = soup.find_all('meta', attrs={"name": "author"})

# Print the attributes of each matching <meta> tag
for meta in author_meta_tags:
    print(meta.attrs)

Output:


{'name': 'author', 'content': 'John Doe'}
    

Example 4: Find <meta> Tags with Charset Attribute


# Find <meta> tags with a charset attribute
charset_meta_tags = soup.find_all('meta', attrs={"charset": "UTF-8"})

# Print the attributes of each matching <meta> tag
for meta in charset_meta_tags:
    print(meta.attrs)

Output:


{'charset': 'UTF-8'}