Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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_Html_Beautifulsoup - Fatal编程技术网

在python beautifulsoup中创建新标记

在python beautifulsoup中创建新标记,python,html,beautifulsoup,Python,Html,Beautifulsoup,我需要在HTML文件中创建新的标记,并向它们添加信息。我按照beautifulsoup文档中给出的示例编写了以下python代码,但它不起作用。我哪里做错了 from bs4 import BeautifulSoup with open("content.htm") as insert: content = BeautifulSoup(insert, "html.parser") #Find the tag you wish to append to. original

我需要在HTML文件中创建新的标记,并向它们添加信息。我按照beautifulsoup文档中给出的示例编写了以下python代码,但它不起作用。我哪里做错了

from bs4 import BeautifulSoup
with open("content.htm") as insert:
    content = BeautifulSoup(insert, "html.parser")

    #Find the tag you wish to append to.
    original_tag = content.find("body")

    #Create & append new tags.
    new_tag = content.new_tag("button", class="accordion")
    original_tag.append(new_tag)

    new_tag = content.new_tag("div", class="panel")
    original_tag.append(new_tag)

    new_tag = content.new_tag("p")
    original_tag.append(new_tag)

print(content)
我希望在以下两个标签之间添加上述3个新标签:

<body></body>


HTML文档的一部分。它不起作用。我哪里做错了?上面的类“accordion”和“panel”被添加到标签中,并由另一个javascript程序使用。

。另一个标签
。最终标签
?你不能那样做。而
class
是一个保留名称,请改用
class
。我将代码改为上面的,它仍然不起作用。你能给出一个代码示例吗?我刚刚测试了你的代码,它工作得很好,如果你将
class
替换为
class
,而这违背了它的目的,那么“accordion”和“panel”类都将被另一个javascript使用。有没有其他方法可以将类添加到标记中?你是对的,新标记有一个
class\uu
属性,很抱歉我错过了。但是您可以在创建标记后添加“class”属性。例如,创建标记:
new\u tag=content.new\u tag(“div”)
并添加类:
new\u tag[“class”]=“panel”