You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

  1. Keep adding the async attribute with an empty string value (just like you did)
  2. When rendering the soup to HTML, use the html5 formatter—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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:16:07