soup.select()在源代码中的原型为:
select(self, selector, namespaces=None, limit=None, **kwargs)
功能:查找html中我们所需要的内容
我们主要使用的参数是selector,其定义为”包含CSS选择器的字符串“。关于CCS,也需要了解一些概念,参考CCS语法与CSS Id 和 Class。
我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select()。如下代码(如h1,p等为标签.center为类名,#para1为id):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<style>
.center
{
text-align:center;
}
#para1
{
text-align:center;
color:red;
}
</style>
</head>
<body>
<h1 class="center">标题居中</h1>
<p id="para1">红色段落居中。</p>
</body>
</html>
以下是将要用到的代码
from bs4 import BeautifulSoup
html = """
<html>
<head> <title> The Dormouse's story </title> </head>
<body>
<p class="title" name="dromouse"> <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"> ... </p>
</body>
</html>
"""
soup = BeautifulSoup(html, 'lxml') # 传入解析器:lxml
soup.select()可通过以下方法进行查找。
1.通过(HTML)标签名查找
print(soup.select('title'))
print(soup.select('a'))#输出的列表含有多个包含标签<a>的元素
输出为:
[<title>The Dormouse's story</title>]
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
2.通过CCS类选择器查找
print(soup.select('.story'))
输出为
[<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">...</p>]
3.通过CCS id 选择器查找
print(soup.select('#link1'))
输出为:
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
4.组合查找
组合查找和通过标签名与类选择器、id选择器进行查找的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开。
print(soup.select('p #link1'))
输出为:
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
5.子标签查找
父标签与子标签之间通过" > "表示递进关系
print(soup.select('p > b'))
输出为:
[<b>The Dormouse's story</b>]
通过子标签查找时的注意事项:soup.select()尽量不使用完整selector
6.通过属性查找
还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。
# 通过href属性及其值进行查找
print(soup.select('a[href="http://example.com/elsie"]'))
输出为:
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]