1.导入
from bs4 import BeatifulSoup
2.实例化BeautifulSoup对象
soup = BeautifulSoup(makeup, feature)
makeup html代码 或者 保存html代码的文件对象
feature html解析器类型,包括'lxml',‘html5lib’,不传入参数就是默认解析器
3.BeautifulSoup选择器
作用:查找、定位元素、并获取数据
分类:
节点选择器 获取数据的基本方法
方法选择器 、css选择器 查找、定位元素的常用选择
4.节点选择器
选取元素的方法:使用tag对象来选择节点元素
格式:soup.tag(soup是BeautifulSoup的实例)
—— 如果有多个相同的节点,soup.tag只会获取到第一个节点
提取信息的方法:
soup.tag.name 获取名称 返回字符串
soup.tag.attrs 获取属性 返回字典(但键是'class'时值是一个列表)
soup.tag.string 获取内容 返回字符串
"""官方演示"""
soup.title
# <title>The Dormouse's story</title>
soup.title.name
# u'title'
soup.title.string
# u'The Dormouse's story'
soup.title.parent.name
# u'head'
soup.p
# <p class="title"><b>The Dormouse's story</b></p>
soup.p['class']
# u'title'
soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
html_str = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
# 1.导入BeautifulSoup类
from bs4 import BeautifulSoup
# 2.传入参数,实例化类
soup = BeautifulSoup(html_str, 'lxml')
# 3.定位元素title
print(soup.title)
# <title>The Dormouse's story</title>
# 4.查看获取到的类型
print(type(soup.title))
# <class 'bs4.element.Tag'> 这里获取到的是Tag类型