如果你使用的是 Python 的第三方库 BeautifulSoup 来解析网页内容,那么你可以使用 prettify()
方法来保留网页中的特殊符号。
例如:
from bs4 import BeautifulSoup
html_doc = '<html><body><p>Hello, world!<br>This is a test.</p></body></html>'
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
输出结果为:
<html>
<body>
<p>
Hello, world!
<br>
This is a test.
</p>
</body>
</html>
也就是说,prettify()
方法会将网页中的 HTML 代码缩进并保留其中的特殊符号。
如果你使用的是其他解析库,那么你可以使用相应的方法来保留特殊符号。比如,如果你使用的是 PyQuery,你可以使用 html()
方法来获取保留了特殊符号的 HTML 代码。