如何用Python BeautifulSoup为标签添加无值的async属性
Ah, I see the issue here! When you set newTag.attrs['async'] = '', BeautifulSoup uses its default HTML formatter which outputs empty-string attributes with quotes, giving you async="". But what you want is the HTML5-style boolean attribute where just the attribute name is present (no value needed).
The fix is straightforward, and it involves adjusting how you output the parsed content:
Step-by-Step Solution
- Keep adding the
asyncattribute with an empty string value (just like you did) - When rendering the soup to HTML, use the
html5formatter—this tells BeautifulSoup to follow modern HTML5 rules for boolean attributes, which don’t require a value.
Working Code Example
from bs4 import BeautifulSoup # Your original script tag html = '<script type="text/javascript" src="bootstrap.min.js" ></script>' soup = BeautifulSoup(html, 'html.parser') script_tag = soup.find('script') # Add the async attribute (empty string value is fine) script_tag['async'] = '' # Output using HTML5 formatter to get the desired result print(soup.prettify(formatter='html5'))
This will output exactly what you're looking for:
Why This Works
In HTML5, boolean attributes like async, defer, or disabled are considered "true" simply by existing in the tag—they don’t need an explicit value. BeautifulSoup’s default html formatter follows older HTML conventions that require attributes to have values, hence the empty quotes. Switching to the html5 formatter aligns the output with modern standards.
If you don’t want pretty-printed output, you can use these alternatives:
# For Python 3.8 and below print(str(soup.encode(formatter='html5'), 'utf-8')) # For Python 3.9+ print(soup.encode(formatter='html5').decode())
内容的提问来源于stack exchange,提问作者Milix

