从零开始写Python爬虫 -1.2 BS4库的安装与使用

Beautiful Soup库一般称为bs4库,支持Python3,是我们写爬虫非常好的第三方库。
bs4库的简单使用
假设我们需要爬取的HTML是如下这么一段:

<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
http://example.com/elsie" class="sister" id="link1">Elsie,
http://example.com/lacie" class="sister" id="link2">Lacie and
http://example.com/tillie" class="sister" id="link3">Tillie;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
</html>

下面我们开始用bs4库解析这一段HTML网页代码

from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'html.parser')
print(soup.prettify())

运行后发现bs4库将网页文件变成了一个soup到类型。*bs4库是解析、遍历、维护、“标签树”的功能库。*通俗一点说就是:bs4库把HTML源代码重新进行了格式化,从而方便我们对其中到节点、标签、属性等进行操作。

#找到文档的title
soup.title
# <title>The Dormouse's story</title>

#title的name值
soup.title.name
# u'title'

#title中的字符串String
soup.title.string
# u'The Dormouse's story'

#title的父亲节点的name属性
soup.title.parent.name
# u'head'

#文档的第一个找到的段落
soup.p
# <p class="title"><b>The Dormouse's story</b></p>

#找到的p的class属性值
soup.p['class']
# u'title'

#找到a标签
soup.a
# http://example.com/elsie" id="link1">Elsie

#找到所有的a标签
soup.find_all('a')
# [http://example.com/elsie" id="link1">Elsie,
#  http://example.com/lacie" id="link2">Lacie,
#  http://example.com/tillie" id="link3">Tillie]

#找到id值等于3的a标签
soup.find(id="link3")
# http://example.com/tillie" id="link3">Tillie

bs4解析HTML原文件的过程:

  • 首先把HTML源文件转换为soup类型
  • 接着从中通过特定的方式抓取内容

更高级的用法

从文档中找到所有标签的链接

for link in soup.find_all('a'):
print(link.get('href'))	

从文档中获取所有文字内容

print(soup.get_text())

猜你喜欢

转载自blog.csdn.net/strawqqhat/article/details/89356385
今日推荐