Attributes

tag["href"], .get, .has_attr, and attrs.

Tags store attributes in a dict. tag["href"] raises if the attribute is missing. tag.get("href") returns None. Multi-valued class is a list.

Goal

Read href, use get, and print the class list.

get vs brackets

html = """
<a href="/nairobi/" title="City">Nairobi</a>
<p>No link here.</p>
"""
soup = BeautifulSoup(html, "html.parser")
a = soup.a
print(a["href"])
print(a.get("href"))
print(a.get("rel"))
print(a.has_attr("title"))
print(a.attrs)

class is a list

html = '<li class="item sold-out">Samosa</li>'
soup = BeautifulSoup(html, "html.parser")
li = soup.li
print(li.get("class"))
print("sold-out" in li.get("class", []))

data-sku and other data-* names work with li.get("data-sku").

html = '<li class="item" data-sku="A">Chai</li>'
soup = BeautifulSoup(html, "html.parser")
print(soup.li.get("data-sku"))
Pitfall

tag["class"] is a list, not a string. "item sold-out" == tag["class"] is False.