BeautifulSoup – 附加到标签的内容
先决条件: Beautifulsoup
Beautifulsoup 是一个Python库,用于从网页中提取内容。它用于从 HTML 和 XML 结构中提取内容。要使用这个库,我们需要先安装它。在这里,我们要将文本附加到标签的现有内容中。我们将在 BeautifulSoup 库的帮助下做到这一点。
方法
- 导入模块
- 打开 HTML 文件
- 阅读内容
- 将内容附加到所需的标签
- 保存对文件的更改
使用的函数:
Beautifulsoup 模块的附加函数用于将内容附加到所需的标签。
句法:
append(“
使用的文件:
HTML
Append
Append to the
We are going to append to the contents using
Geeks For
Python3
# Python program to append to the contents of tag
# Importing library
from bs4 import BeautifulSoup
# Opening and reading the html file
file = open("gfg.html", "r")
contents = file.read()
soup = BeautifulSoup(contents, "lxml")
# Appending to the contents of 'title' tag in html file
print("Current content in title tag is:-")
print(soup.title)
soup.title.append("Using BS")
print("Content after appending is:-")
print(soup.title)
print("\n")
# Appending to the contents of 'h1' tag in html file
print("Current content in heading h1 tag is:-")
print(soup.h1)
soup.h1.append("contents of tag")
print("Content after appending is:-")
print(soup.h1)
print("\n")
# Appending to the contents of 'p' tag in html file
print("Current content in paragraph p tag is:-")
print(soup.p)
soup.p.append("BeautifulSoup library")
print("Content after appending is:-")
print(soup.p)
print("\n")
# Appending to the contents of 'a' tag in html file
print("Current content in anchor a tag is:-")
print(soup.a)
soup.a.append("Geeks Website")
print("Content after appending is:-")
print(soup.a)
# Code to save the changes in 'output.html' file
savechanges = soup.prettify("utf-8")
with open("output.html", "wb") as file:
file.write(savechanges)
Python代码:
蟒蛇3
# Python program to append to the contents of tag
# Importing library
from bs4 import BeautifulSoup
# Opening and reading the html file
file = open("gfg.html", "r")
contents = file.read()
soup = BeautifulSoup(contents, "lxml")
# Appending to the contents of 'title' tag in html file
print("Current content in title tag is:-")
print(soup.title)
soup.title.append("Using BS")
print("Content after appending is:-")
print(soup.title)
print("\n")
# Appending to the contents of 'h1' tag in html file
print("Current content in heading h1 tag is:-")
print(soup.h1)
soup.h1.append("contents of tag")
print("Content after appending is:-")
print(soup.h1)
print("\n")
# Appending to the contents of 'p' tag in html file
print("Current content in paragraph p tag is:-")
print(soup.p)
soup.p.append("BeautifulSoup library")
print("Content after appending is:-")
print(soup.p)
print("\n")
# Appending to the contents of 'a' tag in html file
print("Current content in anchor a tag is:-")
print(soup.a)
soup.a.append("Geeks Website")
print("Content after appending is:-")
print(soup.a)
# Code to save the changes in 'output.html' file
savechanges = soup.prettify("utf-8")
with open("output.html", "wb") as file:
file.write(savechanges)
输出: