BS4是Python中一个用于从HTML或XML文件中提取数据的库,它提供了一种方便的方法来解析、遍历、搜索、修改文档的树形结构。

一、安装导入:

使用包管理器进行安装:

pip3 install beautifulsoup4

导入:

from bs4 import BeautifulSoup

beautifulsoup的解析器:html.parser、lxml、html5lib

默认为:html.parser

二、基本语法及案例

由于bs是针对标签提取数据,所以主要语法是围绕着标签的

比如有如下一组数据:

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 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>
'''

BeautifulSoup(html, 'lxml')这行代码实际上是在调用BeautifulSoup类并创建一个新的对象,该对象代表了整个HTML或XML文档的内容。这个对象被赋值给变量soup,之后你就可以使用soup来访问和操作文档的内容了。

soup=BeautifulSoup(html,'lxml')

参数一是目标数据参数二是解析器。此时soup中就放了完整结构的html数据。

接下来我们就可以对数据操作了。

比如我们要拿到title标签,打点调用即可:

print(soup.title)

输出:

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

如果只想要内部的文字,需要string属性:

print(soup.title.string)

如果想得到标签的名字,需要name属性:

print(soup.title.name)

attrs会返回标签中的所有属性,返回的值是字典,这样我们就可以对属性进行操作了,还会根据属性的性质决定返回的类型。比如我们想得到p标签的name属性值:

print(soup.p.attrs['name'])

这样就会得到:dromouse,其他属性值获取方式也相同,但返回值类型不同,比如class这种属性值可以复用的,可能出现多个所以会返回一个列表类型,而name返回的是字符串类型。

如果页面中有重复的标签,比如p标签,那么使用本文方式只能获得第一个。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部