Python爬虫bs4的基本使用

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

一、安装导入:

使用包管理器进行安装:

复制代码
pip3 install beautifulsoup4

导入:

复制代码
from bs4 import BeautifulSoup

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

默认为:html.parser

二、基本语法及案例

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

比如有如下一组数据:

python 复制代码
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来访问和操作文档的内容了。

python 复制代码
soup=BeautifulSoup(html,'lxml')

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

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

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

python 复制代码
print(soup.title)

输出:

html 复制代码
<title>The Dormouse's story</title>

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

python 复制代码
print(soup.title.string)

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

python 复制代码
print(soup.title.name)

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

python 复制代码
print(soup.p.attrs['name'])

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

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

相关推荐
未来可期叶2 小时前
如何用Python批量解压ZIP文件?快速解决方案
python
张槊哲3 小时前
ROS2架构介绍
python·架构
风逸hhh3 小时前
python打卡day29@浙大疏锦行
开发语言·前端·python
浩皓素3 小时前
深入理解For循环及相关关键字原理:以Python和C语言为例
c语言·python
英英_3 小时前
详细介绍一下Python连接MySQL数据库的完整步骤
数据库·python·mysql
ᖰ・◡・ᖳ4 小时前
JavaScript:PC端特效--缓动动画
开发语言·前端·javascript·css·学习·html5
水花花花花花4 小时前
GloVe 模型讲解与实战
python·深度学习·conda·pip
C_VuI4 小时前
如何安装cuda版本的pytorch
人工智能·pytorch·python
Star abuse4 小时前
机器学习基础课程-6-课程实验
人工智能·python·机器学习
hy____1234 小时前
C++多态的详细讲解
开发语言·c++