预约成功
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:
(1)Tag
(2)NavigableString
(3)BeautifulSoup
(4)Comment
1、python的BeautifulSoup对象类型有哪些——Tag
Tag 通俗点讲就是 HTML 中的一个个标签,例如:
from bs4 import BeautifulSoup
html = """
first item
second item
third item
fourth item
fifth item
"""
# 创建 Beautiful Soup 对象
soup = BeautifulSoup(html, "lxml")
print(soup.li) #
first item
print(soup.a) # first item
print(soup.span) # third item
print(soup.p) # None
print(type(soup.li)) #
我们可以利用 soup 加标签名轻松地获取这些标签的内容,这些对象的类型是bs4.element.Tag。但是注意,它查找的是在所有内容中的第一个符合要求的标签。如果要查询所有的标签,后面会进行介绍。
对于 Tag,它有两个重要的属性,是name和attrs。
from bs4 import BeautifulSoup
html = """
first item
second item
third item
fourth item
fifth item
"""
# 创建 Beautiful Soup 对象
soup = BeautifulSoup(html, "lxml")
print(soup.li.attrs) # {'class': ['item-0']}
print(soup.li["class"]) # ['item-0']
print(soup.li.get('class')) # ['item-0']
print(soup.li) #
first item
soup.li["class"] = "newClass" # 可以对这些属性和内容等等进行修改
print(soup.li) #
first item
del soup.li['class'] # 还可以对这个属性进行删除
print(soup.li) #
first item
2、python的BeautifulSoup对象类型有哪些——NavigableString
既然我们已经得到了标签的内容,那么问题来了,我们要想获取标签内部的文字怎么办呢?很简单,用 .string 即可,例如
from bs4 import BeautifulSoup
html = """
first item
second item
third item
fourth item
fifth item
"""
# 创建 Beautiful Soup 对象
soup = BeautifulSoup(html, "lxml")
print(soup.li.string) # first item
print(soup.a.string) # first item
print(soup.span.string) # third item
# print(soup.p.string) # AttributeError: 'NoneType' object has no attribute 'string'
print(type(soup.li.string)) #
3、python的BeautifulSoup对象类型有哪些——BeautifulSoup
BeautifulSoup 对象表示的是一个文档的内容。大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性来感受一下。
from bs4 import BeautifulSoup
html = """
first item
second item
third item
fourth item
fifth item
"""
# 创建 Beautiful Soup 对象
soup = BeautifulSoup(html, "lxml")
print(soup.name) # [document]
print(soup.attrs) # {}, 文档本身的属性为空
print(type(soup.name)) #
4、python的BeautifulSoup对象类型有哪些——Comment
Comment 对象是一个特殊类型的 NavigableString 对象,其输出的内容不包括注释符号。
from bs4 import BeautifulSoup
html = """
"""
# 创建 Beautiful Soup 对象
soup = BeautifulSoup(html, "lxml")
print(soup.a) #
print(soup.a.string) # Elsie
print(type(soup.a.string)) #
a 标签里的内容实际上是注释,但是如果我们利用 .string 来输出它的内容时,注释符号已经去掉了。
以上就是《python的BeautifulSoup对象类型有哪些?这是你进阶python学习的关键》的全部内容,这些python的实践方法学会了,你的python一定会突飞猛进,环球网校的小编也祝大家python学习之路顺利。如果你想知道更多的python编程知识,可以点击下方资料下载链接。