python - 如何获取文本并替换某些标签之间的文本

标签 python html regex html-parsing

给定一个字符串

"<p> >this line starts with an arrow <br /> this line does not </p>"

"<p> >this line starts with an arrow </p> <p> this line does not </p>"

如何找到以箭头开头并用 div 包围的行

这样就变成了:

"<p> <div> >this line starts with an arrow </div> <br /> this line does not </p>

最佳答案

由于您要解析的是 HTML,因此请使用工具来完成这项工作 - HTML 解析器,例如 BeautifulSoup .

使用find_all()查找以 >wrap() 开头的所有文本节点它们带有一个新的 div 标签:

from bs4 import BeautifulSoup

data = "<p> >this line starts with an arrow <br /> this line does not </p>"

soup = BeautifulSoup(data)
for item in soup.find_all(text=lambda x: x.strip().startswith('>')):
    item.wrap(soup.new_tag('div'))

print soup.prettify()

打印:

<p>
    <div>
    >this line starts with an arrow
    </div>
    <br/>
    this line does not
</p>

关于python - 如何获取文本并替换某些标签之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24391547/

相关文章:

python - 关于 MySQLdb conn.autocommit(True)

python - 没有德语词典的 PyEnchant

python - basemap 返回空白 map

html - 垂直列表(从水平返回到默认值)

javascript - 如何在 Codemirror 中使用正则表达式来匹配段落的第一个和最后一个单词?

javascript - 用字符串替换多个相同的字符

Python 错误 : Cannot import name KafkaConsumer

javascript - 在HTML表单中添加JavaScript计算功能

html - Bulma - 列大小为一半仍适用于具有 is-desktop 类的平板电脑模式

javascript - 如果长度为空,则需要通过一个条件