Is there any way I can perserve HTML entities in the source when parsing it with BeautifulSoup?
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p class="test">"Hello World!" I said')
print(soup.string)
# Outputs: '"Hello World!" I said'
# Wanted/Expected: '"Hello World!" I said'
Also, when writing those preserved html entities back to a file. Will f.write(str(soup)) do? The following code to is meant produce an identical copy of the original, which currently isn't:
from bs4 import BeautifulSoup
from pathlib import Path
# The original contains tons of HTML entities
original = Path("original.html")
output = Path("duplicate.html")
with open(original, "rt", encoding="utf8") as f:
soup = BeautifulSoup(f, "lxml")
with open(output, "wt", encoding="utf8") as f:
f.write(str(soup))