我有一组 HTML 文件,我想在每个文件中提取第一个标签。由于文件没有始终位于文件第一个的特定标记,因此我不确定如何执行此操作。
例如,对于以下代码段,第一个标签为 <html> .
<html>
<head>
<title>
insert title here
</title>
</head>
</html>
有什么方法可以使用 BeautifulSoup(或可能是其他工具)来完成此操作?提前致谢:)
请您参考如下方法:
在这种情况下,您可以使用 BeautifulSoup,只需发出 find()在 BeautifulSoup 对象上 - 它会找到树中的第一个元素。 .name会给你标签名称:
from bs4 import BeautifulSoup
data = """
<html>
<head>
<title>
insert title here
</title>
</head>
</html>
"""
soup = BeautifulSoup(data, "html.parser")
print(soup.find().name)
