Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python beautifulsoup add attribute to tag without value

I need to add async attribute to the tag using beautifulsoup and python.

given this:

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

I need to get this:

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

I'm trying this:

newTag.attrs['async'] = ''

but the result is:

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

Any help much appreciated.

like image 887
Milix Avatar asked Jan 28 '23 05:01

Milix


1 Answers

Try using 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)

This produces the following output:

<meta async="" charset="utf-8"/>
<meta async charset="utf-8"/>
like image 162
Mihai Chelaru Avatar answered Jan 31 '23 07:01

Mihai Chelaru