Yeah, you can do something like this. There are probably lots of ways to do this, this is just one.
from bs4 import BeautifulSoup, Tag import random with open('scram.html') as file: html_content = file.read() soup = BeautifulSoup(html_content, 'html.parser') def get_position(tag): """Get the position of the p tag and return the parent and the position under the parent.""" parent = tag.parent for e, child in enumerate(parent.children): if isinstance(child, Tag) and child is tag: return parent, e raise RuntimeError('Could not find tag position under a parent') p_tags = soup.css.select('p') tag_positions = [get_position(p) for p in p_tags] random.shuffle(tag_positions) for pos, p in zip(tag_positions, p_tags): parent, index = pos parent.insert(index, p) with open('scram2.html', 'wb') as file: file.write(soup.encode())