Skip to content

EXTRACTING ATTRIBUTES - Getting tag attributes

Python
#!/usr/bin/env python3
"""EXTRACTING ATTRIBUTES - Getting tag attributes"""
from bs4 import BeautifulSoup
html = """
<html><body>
<a href="https://example.com" class="link" id="main-link">Link</a>
<img src="image.jpg" alt="Description" width="100">
<input type="text" name="username" value="john">
</body></html>
"""
soup = BeautifulSoup(html, 'html.parser')
print("Extracting Attributes:")
link = soup.find('a')
print(f"  href: {link.get('href')}")
print(f"  class: {link.get('class')}")
print(f"  id: {link['id']}")
img = soup.find('img')
print(f"  src: {img['src']}")
print(f"  alt: {img['alt']}")
print(f"  All attrs: {img.attrs}")