我有一个这样的文件:
words1 outside of a Tag <tag1> words2 inside of tag1 </tag1> words3 outside of a Tag
我想提取 tag1
之外的字符串,并使用 beautifulsoup 将其更改为如下所示:
changed word1 <tag1> words2 inside of tag1 </tag1> changed word3
如何用 beautifulSoup 替换标签中的单词?
最佳答案
文本元素也被视为父元素的子元素。
如果找到 tag1
,则可以在属性 .previousSibling
和 .nextSibling
中找到前后文本。或者,您可以找到父标签,然后选择适当的子标签。
示例:
from bs4 import BeautifulSoup
# assuming BeautifulSoup 4
doc = """
words1 outside of a Tag <tag1>words2 inside of tag1</tag1>
words3 outside of a Tag
"""
soup = BeautifulSoup(doc, 'html.parser')
tag = soup.find('tag1')
tag.previousSibling.replaceWith('changed word1 ')
tag.nextSibling.replaceWith(' changed word3')
print(soup)
关于python - 如何使用 Beautiful Soup 查找和更改标签之外的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45757641/