常用

html_doc = """
<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 class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story"><!--Hey, buddy. Want to buy a used parser?--></p>
</body></html>
"""
from bs4 import BeautifulSoup
from bs4.element import Comment

使用BeautifulSoup解析这段代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出:

soup = BeautifulSoup(html_doc, 'lxml')

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,
所有对象可以归纳为4种:
Tag
NavigableString
BeautifulSoup
Comment

Tag HTML中的标签 相同的标签只去第一个

4.1 获取标签

soup.title
<title>The Dormouse's story</title>

4.2 获取属性

用途 获取标签内的属性,如herf链接等

# soup.a.attrs
# {'class': ['sister'], 'href': 'http://example.com/elsie', 'id': 'link1'}

# 获取单个属性
print(soup.a['href'])
print(soup.a.attrs['href'])
print(soup.a.get('href'))
print(soup.a['id'])
link1

4.2 获取内容

获取标签内容

print(soup.p.string)
print(soup.a.text)

4.3 BeautifulSoup

BeautifulSoup 对表示的是一个文档的全部内容,大部分时候可以把它当做tag 它支持便利文档树和搜索树的大部分方法
因为beautifulSoup对象并不是真正的HTML的tag,但是他没有name和attribute属性,
但有时查看它的.name属性还是很方便的,BeautifulSoup对象包含一个值为[document]的特殊属性

print(soup.name)
[document]
print(soup.a.name)
a

4.4 comment

comment内容是文档的注释部分, 通常删除注释部分

if type(soup.p.string) == Comment:
print(soup.p.prettify()) # prettify 原样显示
else:
print(soup.p.string)

5 搜索文档树

# BeautifulSoup搜索方法 find() findall()

5.1.1 字符串

# 最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,
# Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的<b>标签

# 返回所有的div标签
# print(soup.find_all('a'))
# 如果传入字节码参数,Beautiful Soup会当作UTF-8编码,可以传入一段Unicode 编码来避免Beautiful Soup解析编码出错

5.1.2 正则表达式

# 如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容

# 下面例子中找出所有以b开头的标签,这表示<body>和<b>标签都应该被找到

# import re
# print(soup.find_all(re.compile("^a")))

5.1.3 列表

如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回

print(soup.find_all(["a", "b"]))

5.1.4 keyword

如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,
如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性.

print(soup.find_all(id='link2'))

5.1.4 安装class搜索

安装css类搜索tag的功能是一个非常实用
返回class等于info的div
print(soup.find_all('a', id="link2"))

5.1.5 安装属性搜索

print(soup.find_all('a', attrs={"id": "link3"}))

6 css选择器扩展

soup.select(参数)

# 表达式                 说明
# tag 选择指定标签
# #id 选择id为container的节点
# .class 选择所有class为container的节点
# li a 选择所有li下的所有a节点
# ul + p (兄弟)选择ul后面第一个p节点
# div#id>ul (父子)选择id为id的dev的第一个ul的子元素
# table~dev 选取与table相邻的所有div元素
# a[title] 选取所有有title属性的a元素
# a[class=" title"] 选取所有class属性为title值的a
# a[href*=" sxt"] 选取所有href属性值包含sxt的a元素
# a[href^=" http"] 选取所有href属性值以http开头的a元素
# a[href$=" .png"] 选取所有href属性值以.png结尾的a元素
# inpput[type="redio"]:cheked 选取选中的hobby的元素


# print(soup.select('title'))
# print(soup.select('#link1'))
# print(soup.select('.sister'))
# print(soup.select('p a')) # print(soup.select('p > a'))
# print(soup.select('title')[0].text)