1. BeautifulSoup介绍与安装
1.1 什么是BeautifulSoup
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过转换器实现惯用的文档导航,查找,修改文档的方式
1.2 如何安装?
首先查看电脑中有没有BeautifulSoup工具包:pip show beautifulsoup4
直接安装:pip install beautifulsoup4
1.3 如何导入BeaitufulSoup?
在代码窗口顶部输入: from bs4 import BeautifulSoup
1.4 官方案例演示
设置变量,输入以下html内容,代码如下
h = """
<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>
"""
soup = BeautifulSoup(h,'lxml')
print(soup)#直接输出
print(soup.prettify())# 标准化输出
直接输出的结果为
标准化输出:
<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">
...
</p>
</body>
</html>
解析标签
查找title标签 | soup.title |
---|---|
输出title标签的名字 | soup.title.name |
查找p标签 | soup.p |
输出p标签中属性class的内容 | soup.p[‘class’] |
查找a标签 | soup.a/soup.find(‘a’) |
查找所有a标签 | soup.find_all(‘a’) |
查找title标签
print(soup.title)
#输出为:
<title>The Dormouse's story</title>
输出title标签的名字
print(soup.title.name)
#输出为:
'tltle'
查找p标签
print(soup.p)
#输出为
<p class="title"><b>The Dormouse's story</b></p>
输出p标签中属性class的内容
print(soup.p['class'])
#输出为
['title']
查找a标签
print(soup.a)
print(soup.find('a'))
#输出为
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
查找所有a标签
print(soup.find_all('a'))
#输出为
[<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>]
直接使用soup.tag(标签)的输出结果和使用soup.find(‘tag’)的输出结果是一样的,而且都是 <class ‘bs4.element.Tag’>数据类型