我正在查找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>
content = x.string
那么content.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
相关问题 更多 >
编程相关推荐