如何在使用Python时在HTML字符串前插入标签

2024-09-30 01:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在查找html文档中的所有文本,我想添加span标记,它包含关于每个文本的一些信息,如下所示

def recursiveChildren(x):
    if "childGenerator" in dir(x):
      for child in x.childGenerator():

          recursiveChildren(child)
    else:

      if not x.isspace():

          content = x.string
          new_tag = soup.new_tag("span")
          content.insert_before(new_tag)
if __name__ == "__main__":

with open("path to html",'r') as file:
      soup = BeautifulSoup(file)
for child in soup.body.childGenerator():
   recursiveChildren(child)

我得到错误,因为字符串对象之前没有属性插入。如何在字符串之前插入标记。我还尝试获取字符串的父标记,并在父标记内容之前添加add span标记,但如果有嵌套标记,则会产生问题,因为我希望在每个独立字符串之前都有一个span标记。有可能吗?类似于下面的但是在Python中Insert span tag before # content text

Adding Span before specific string with jQuery

Html示例:

^{pr2}$

我想要的输出

<p class=MsoNormal >**<span>**This is first string</span> <b>**<span>** Second String </span></b>**<span>** , </span><span style='font-family:"Times New Roman"><o:p></o:p></span></p>

Tags: 字符串in标记childnewstringifhtml
1条回答
网友
1楼 · 发布于 2024-09-30 01:18:42

content = x.string那么content.insert_before(new_tag)就是你的问题了。在

if not x.isspace():
    new_tag = soup.new_tag("span")
    x.insert_before(new_tag)

soup.body.childGenerator()返回bs4.element的列表。它们能够执行复杂的操作,比如您要执行的插入操作。在

这就是您的函数recursiveChildren得到的参数x。所以x能够insert_before。在

但是,当执行content = x.string时,您将在content中存储一个简单的HTML字符串(python中的str类型)。显然,string不支持insert_before-必须在x上执行此操作。在


顺便说一句,你应该看看PEP8-recursiveChildren最好命名为recursive_children,而{}是一个错误的变量名,你应该将它命名为element或类似的名称。在

Explicit is better than implicit

相关问题 更多 >

    热门问题