【问题标题】:python beautifulsoup add attribute to tag without valuepython beautifulsoup将属性添加到没有值的标签
【发布时间】:2018-10-04 02:53:08
【问题描述】:

我需要使用beautifulsoup和python为标签添加异步属性。

鉴于此:

<script type="text/javascript" src="bootstrap.min.js" ></script>

我需要得到这个:

<script async type="text/javascript" src="bootstrap.min.js" ></script>

我正在尝试这个:

newTag.attrs['async'] = ''

但结果是:

<script async="" type="text/javascript" src="bootstrap.min.js" ></script>

非常感谢任何帮助。

【问题讨论】:

  • 你能给我们一个minimal reproducible example,包括所有相关的版本号吗?当我尝试这个,做显而易见的事情时,它起作用了。如果您正在做一些奇怪的事情来获取汤,或者使用旧版本或前沿版本,我们需要知道这一点才能调试它。
  • 我认为这不是有效的 xml,我不希望你可以。

标签: python html beautifulsoup tags


【解决方案1】:

尝试使用newTag.attrs['async'] = None

from urllib import request
f = request.urlopen("http://www.example.com")
s = f.read()
f.close()

from bs4 import BeautifulSoup
soup = BeautifulSoup(s, "lxml")

newTag = soup.find("meta", charset = "utf-8")

tagCopy = newTag

newTag.attrs['async'] = ""
print(newTag)

tagCopy.attrs['async'] = None
print(tagCopy)

这会产生以下输出:

<meta async="" charset="utf-8"/>
<meta async charset="utf-8"/>

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2017-11-27
    • 2022-09-24
    相关资源
    最近更新 更多