首先,安装Beautifulsoup

pip install beautifulsoup4


然后初始化对象

from bs4 import BeautifulSoup

file = BeautifulSoup(open("index.html")) #此处传入文件,红色部分为要传入的页面源码文件

string = BeautifulSoup("<html>data</html>") #此处红色部分传入一个字符串


可以通过 .标签名 向下深入, 如 : file.p.a.span


遍历:

html 文件有标签,字符串等组成,遍历时可以同级遍历,也可以跨级遍历。

同级遍历: .previous_sibling

.next_sibling


跨级遍历:

向父级遍历:

.parent

向子级遍历:

.contents #以列表形式遍历,通过一个列表将结果展示出来

.children #以生成器形式遍历,比较节省内存