如何用Python、BeautifulSoup构建子树?
我正在尝试使用BeautifulSoup来撰写网页 当我通过如何用Python、BeautifulSoup构建子树?,python,beautifulsoup,Python,Beautifulsoup,我正在尝试使用BeautifulSoup来撰写网页 当我通过string设置标记的内部内容时,它会自动转义字符串。我还没有找到一种技术,比如htmlmethod/attribute,其中BS不会自动转义所有内容 from bs4 import BeautifulSoup f = open("template.html", "r") soup = BeautifulSoup(f.read(), 'html.parser') f.close() x = soup.find("div", id="
string
设置标记的内部内容时,它会自动转义字符串。我还没有找到一种技术,比如html
method/attribute,其中BS不会自动转义所有内容
from bs4 import BeautifulSoup
f = open("template.html", "r")
soup = BeautifulSoup(f.read(), 'html.parser')
f.close()
x = soup.find("div", id="example")
x.string("<div>example</div>")
# x's contents...
# <div id="example"><div>example</div></div>
从bs4导入美化组
f=打开(“template.html”、“r”)
soup=BeautifulSoup(f.read(),'html.parser')
f、 关闭()
x=soup.find(“div”,id=“example”)
x、 字符串(“示例”)
#x的内容。。。
#div示例/div
很明显,BS更常用于抓取HTML而不是构建HTML–是否有用于构建HTML的公共库?您应该试试。然后可以按如下方式渲染模板:
来自jinja2导入模板的
t=模板({{example_div}}})
t、 渲染(示例_div='example')
导致:
“示例”
当然,您也可以从文件中读取模板:
以open('template.html','r')作为f的:
t=模板(f.read())
当然要检查这个啊。我用过很多Jinja,但没有在烧瓶上下文之外想到它。