给定一个字符串
"<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/