Nanfeng

Notes on software development, code, and curious ideas

Inserting Content into HTML with Beautiful Soup

Manually modifying index.html after every Cocos Creator web export is repetitive and error-prone. Python and Beautiful Soup can automate it.

Install the dependencies:

1
pip install beautifulsoup4 lxml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from bs4 import BeautifulSoup

def insert_code_in_html(file_path):
head_code = '''
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<style>
html, body, #GameDiv, #Cocos3dGameContainer, #GameCanvas {
width: 100%; height: 100%; margin: 0;
}
</style>
'''
body_code = '''
<div id="loading-animation"><img src="web.png" alt="Loading"></div>
<div id="loading-text">Loading may take a few seconds. Please be patient.</div>
<script>
const tg = window.Telegram.WebApp;
tg.isClosingConfirmationEnabled = true;
</script>
'''

with open(file_path, 'r', encoding='utf-8') as source:
soup = BeautifulSoup(source, 'lxml')

if soup.head:
soup.head.append(BeautifulSoup(head_code, 'html.parser'))
if soup.body:
soup.body.append(BeautifulSoup(body_code, 'html.parser'))

with open(file_path, 'w', encoding='utf-8') as output:
output.write(str(soup))

insert_code_in_html('web-mobile/index.html')

Do not name the script html.py; that shadows Python’s standard html package and can cause a circular-import error while importing Beautiful Soup.

+