Python 3爬虫网易云(二)—— BeautifulSoup库用法上篇

本文介绍如何使用BeautifulSoup模块从HTML文档中提取所需数据。通过示例展示了如何获取标签、属性及文本等内容,并介绍了Tag、NavigableString等核心概念。

写在前面

上一篇演示了如何使用requests模块向网站发送http请求,获取到网页的HTML数据。这篇来演示如何使用BeautifulSoup模块来从HTML文本中提取我们想要的数据。

运行环境

我的运行环境如下:系统版本:Windows10。Python版本:Python3.6   IDE:Pycharm

BeautifulSoup ——解析html文档

首先来看BeautifulSoup的对象种类,在使用的过程中就会了解你获取到的东西接下来应该如何操作。
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象。所有对象可以归纳为4种类型:Tag , NavigableString , BeautifulSoup , Comment 。下面我们分别看看这四种类型都是什么东西。

1>.Tag

这个就跟HTML或者XML(还能解析XML?是的,能!)中的标签是一样一样的。我们使用find()方法返回的类型就是这个(插一句:使用find-all()返回的是多个该对象的集合,是可以用for循环遍历的。)。返回标签之后,还可以对提取标签中的信息。

提取标签的名字:

tag.name


提取标签的属性:

tag['attribute']


我们用一个例子来了解这个类型:

from bs4 import BeautifulSoup

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 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(html_doc, 'lxml')  #声明BeautifulSoup对象
find = soup.find('p')  #使用find方法查到第一个p标签
print("find's return type is ", type(find))  #输出返回值类型
print("find's content is", find)  #输出find获取的值
print("find's Tag Name is ", find.name)  #输出标签的名字
print("find's Attribute(class) is ", find['class'])  #输出标签的class属性值
运行结果如下:
find's return type is  <class 'bs4.element.Tag'>
find's content is <p class="title"><b>The Dormouse's story</b></p>
find's Tag Name is  p
find's Attribute(class) is  ['title']


2>.NavigableString

NavigableString就是标签中的文本内容(不包含标签)。获取方式如下:
tag.string

还是以上面那个例子,加上下面这行,然后执行:
print('NavigableString is:', find.string)

结果得到的是
NavigableString is: The Dormouse's story

3>.BeautifulSoup

BeautifulSoup对象表示一个文档的全部内容。支持遍历文档树和搜索文档树

4>.Comment

这个对象其实就是HTML和XML中的注释
from bs4 import BeautifulSoup
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
soup = BeautifulSoup(markup)
comment = soup.b.string
print(comment)
print(type(comment))

结果如下

Hey, buddy. Want to buy a used parser?
<class 'bs4.element.Comment'>















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值