When working with BeautifulSoup in Python, the class attribute of an HTML element is stored as a list of strings. This means that if you want to add a new class (e.g., "no-bbox"), you must treat the class attribute as a list and modify it accordingly.
✅ Correct Approach
If you have a BeautifulSoup element like:
from bs4 import BeautifulSoup
html = '<div class="existing-class">Some content</div>'
soup = BeautifulSoup(html, 'html.parser')
element = soup.find('div')
You can add a new class to it like this:
element["class"].append("no-bbox")
This will result in:
<div class="existing-class no-bbox">Some content</div>
❌ What's Wrong with the Original Code?
Your original code:
element["class"] += "no-bbox"
This is incorrect because:
element["class"] is a list of strings.
+= with a string will iterate over each character of the string and add them as separate elements to the list, which is not what you want.
For example:
element["class"] = ["a", "b"]
element["class"] += "c" # This becomes ["a", "b", "c"] (if "c" is a single character)
element["class"] += "no-bbox" # This becomes ["a", "b", "n", "o", "b", "b", "o", "x"]
✅ Alternative: Use += with a List
If you prefer to use +=, make sure you're appending a list:
element["class"] += ["no-bbox"]
This also works and appends "no-bbox" as a single class.
🛡️ Optional: Handle Missing class Attribute
If the element may not have a class attribute, you can safely handle it like this:
if "class" in element.attrs:
element["class"].append("no-bbox")
else:
element["class"] = ["no-bbox"]
Or more concisely:
element["class"] = element.get("class", []) + ["no-bbox"]
✅ Final Recommendation
Use append() for clarity and safety:
element["class"].append("no-bbox")
This is the most direct and idiomatic way to add a class using BeautifulSoup.