This is paragraph 1.
This is paragraph 2.
This is paragraph 3.
以下是一个示例代码,演示如何遍历通过标签选择的内容控件,并用单个值替换它们的文本。
from bs4 import BeautifulSoup
html = """
This is paragraph 1.
This is paragraph 2.
This is paragraph 3.
"""
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html, 'html.parser')
# 选择所有的标签
paragraphs = soup.find_all('p')
# 遍历选择的
标签,并替换它们的文本
replacement_text = "This is the replaced text."
for p in paragraphs:
p.string = replacement_text
# 打印修改后的HTML
print(soup.prettify())
运行上述代码,输出的结果将是:
This is the replaced text.
This is the replaced text.
This is the replaced text.
通过遍历选择的标签,并使用
p.string = replacement_text
语句替换它们的文本内容,我们可以将所有的标签中的文本替换为单个值。