Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Python、BeautifulSoup构建子树?_Python_Beautifulsoup - Fatal编程技术网

如何用Python、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="

我正在尝试使用BeautifulSoup来撰写网页

当我通过
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">&lt;div&gt;example&lt;/div&gt;</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,但没有在烧瓶上下文之外想到它。