1

I'm using beautiful soup to edit an html file. I've been able to add a tag, but I'm having trouble adding my javascript code inside the script element.

I have the following code:

soup = BeautifulSoup(differencehtml, 'html.parser')

# create a new tag
tag = soup.new_tag("script")
tag.append = jscodestring  # this is not adding the javascript to the html file
# tag.string = jscodestring # also tried this unsuccesfully

head = soup.find('head')

#insert new tag after head tag
head.insert_after(tag)

When I inspect the resulting html, it looks like this:

...
</head>
<script>
   </script>
...

Why does append not work? How do I get code inside the script tag?

1
  • See one of the answers in this SO question. Commented Aug 29, 2018 at 19:00

1 Answer 1

1

Append() is used to modify the tags's contents. Look at the documentation here, https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring-and-new-tag .

This line of your code :

tag.append = jscodestring  # this is not adding the javascript to the html file

would need to look like this

tag.append(jscodestring)  # this is not adding the javascript to the html file

Even so, doing this would just place a string value of whatever jscodestring equals inside your tag's contents.

What you are looking to do is add a new attribute to your script tag.

This could be done somewhat like this. I can't see the contents of differencehtml so I cannot be sure.

soup.find('script')['selected'] = '<path to your javascript file>'

Check this post for another example, BeautifulSoup - adding attribute to tag .

(EDIT) To get the code to look like this

<script> Hello World!</script>

you would just need to do tag.append("Hello World!") or place a variable that is a string inside append()

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help! But isn't modifying the contents the same as adding a new attribute? I did the following: soup.find('script')['selected'] = 'C:\\Users\\myname\\Documents\\my_file\\buttons.js and the resulting html looked like this: <script selected="C:\Users\myname\Documents\my_file\buttons.js"> </script>
I would like the code to look like this: <script> 'Hello World!' </script> and not <script selected = 'Hello World!'> </script>
@mir Sorry for misinterpreting. I edited the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.