爬虫学习——bs4库的使用

本文介绍了如何在Python中使用BeautifulSoup4库解析HTML文件,包括安装、解析器的选择、Tag、NavigableString等对象的操作,以及遍历文档树、搜索和CSS选择器的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bs4也就是beautifulsoup4,是python解析html文件的一个好用的第三方库,常被用于爬虫。

一、bs4的安装

pip install beautifulsoup4

阿里国内源安装:

pip install beautifulsoup4 -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com

二、bs4解析器

from bs4 import BeautifulSoup
import requests

url = http://www.example.com  # 要爬取的网址

resp = requests.get(url)  # 请求页面信息

soup = BeautifulSoup(resp.text, 'html.parser')  # 使用BeautifulSoup解析网页内容

其中resp.text是得到的html文件,html.parser是python内置的html解析器,如果没有填写这个参数,会默认这个解析器。

bs4还支持一些第三方解析器:

解析器使用方法优势劣势
Python标准库BeautifulSoup(html,’html.parser’)Python内置标准库;执行速度快在python2.7.3和3.2.2之前的版本中文档容错能力差
lxml html解析器(需要额外导入)BeautifulSoup(html,’lxml’)速度快;容错能力强需要安装C语言库
lxml XML解析器(需要额外导入)BeautifulSoup(html,[‘lxml’,’xml’])或BeautifulSoup(html,’xml’)唯一支持解析xml需要安装C语言库
htm5libBeautifulSoup(html,’htm5llib’)以浏览器方式解析,最好的容错性,生成html5速度慢

三、bs4对html文件的处理

BeautifulSoup4将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

(1)Tag
(2)NavigableString
(3)BeautifulSoup
(4)Comment

(1)Tag : Tag通俗点讲就是HTML中的一个个标签,例如:

from bs4 import BeautifulSoup
soup = BeautifulSoup(resp.text, 'html.parser')

# 获取title标签的所有内容
print(soup.title)

# 获取head标签的所有内容
print(soup.head)

# 获取第一个a标签的所有内容
print(soup.a)

# 类型
print(type(soup.a))

我们可以利用 soup 加标签名轻松地获取这些标签的内容,这些对象的类型是 bs4.element.Tag。
但是注意,它查找的是在所有内容中的第一个符合要求的标签。

对于 Tag,它有两个重要的属性,是 name 和 attrs:

# [document] 
#bs 对象本身比较特殊,它的 name 即为 [document]
print(soup.name)

# head 
#对于其他内部标签,输出的值便为标签本身的名称
print(soup.head.name) 

# 在这里,我们把 a 标签的所有属性打印输出了出来,得到的类型是一个字典。
print(soup.a.attrs)

#还可以利用get方法,传入属性的名称,二者是等价的
print(soup.a['class']) # soup.a.get('class')

# 可以对这些属性和内容等等进行修改
soup.a['class'] = "newClass"
print(soup.a) 

# 还可以对这个属性进行删除
del soup.a['class'] 
print(soup.a)

(2)NavigableString:获取标签内部的文字用 .string 即可,例如:

print(soup.title.string) # 也可以soup.title.text

print(type(soup.title.string))

(3)BeautifulSoup:表示的是一个文档的内容。

大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性,例如:

print(type(soup.name))

print(soup.name)

print(soup.attrs)

(4)Comment:是一个特殊类型的 NavigableString 对象,其输出的内容不包括注释符号。

print(soup.a)  # 此时不能出现空格和换行符,a标签如下:
# <a class="mnav" href="http://news.baidu.com" name="tj_trnews"><!--新闻--></a>

print(soup.a.string) # 新闻

print(type(soup.a.string)) # <class 'bs4.element.Comment'>

四、遍历文档树

(1).contents:获取Tag的所有子节点,返回一个list

# tag的.content 属性可以将tag的子节点以列表的方式输出
print(soup.head.contents)

# 用列表索引来获取它的某一个元素
print(soup.head.contents[1])

(2).children:获取Tag的所有子节点,返回一个生成器

for child in soup.body.children:
    print(child)

五、搜索文档树

1. find_all(name, attrs, recursive, text, **kwargs)

(1)name参数:

字符串过滤:会查找与字符串完全匹配的内容

a_list = soup.find_all("a")
print(a_list)

正则表达式过滤:如果传入的是正则表达式,那么BeautifulSoup4会通过search()来匹配内容

t_list = soup.find_all(re.compile("a"))
for item in t_list:
    print(item)

列表: 如果传入一个列表,BeautifulSoup4将会与列表中的任一元素匹配到的节点返回

t_list = soup.find_all(["meta","link"])
for item in t_list:
    print(item)

方法: 传入一个方法,根据方法来匹配

def name_is_exists(tag):
    return tag.has_attr("name")

t_list = soup.find_all(name_is_exists)
for item in t_list:
    print(item)

(2)kwargs参数:

# 查询id=head的Tag
t_list = soup.find_all(id="head")
print(t_list)

# 查询href属性包含ss1.bdstatic.com的Tag
t_list = soup.find_all(href=re.compile("http://news.baidu.com"))
print(t_list)

# 查询所有包含class的Tag(注意:class在Python中属于关键字,所以加_以示区别)
t_list = soup.find_all(class_=True)
for item in t_list:
    print(item)

(3)attrs参数:

并不是所有的属性都可以使用上面这种方式进行搜索,比如HTML的data-*属性,我们可以使用attrs参数,定义一个字典来搜索包含特殊属性的tag:

t_list = soup.find_all(attrs={"data-foo":"value"})
for item in t_list:
    print(item)

(4)text参数:
通过text参数可以搜索文档中的字符串内容,与name参数的可选值一样。
text参数接受 字符串,正则表达式,列表

t_list = soup.find_all(attrs={"data-foo": "value"})
for item in t_list:
    print(item)

t_list = soup.find_all(text="hao123")
for item in t_list:
    print(item)

t_list = soup.find_all(text=["hao123", "地图", "贴吧"])
for item in t_list:
    print(item)

t_list = soup.find_all(text=re.compile("\d"))
for item in t_list:
    print(item)

(5)limit参数:
传入一个limit参数来限制返回的数量
例如下列放回数量为2

t_list = soup.find_all("a",limit=2)
for item in t_list:
    print(item)

2.find()
返回符合条件的第一个Tag
即当我们要取一个值的时候就可以用这个方法

t = soup.div.div

# 等价于
t = soup.find("div").find("div")

六、CSS选择器

(1)通过标签名查找

print(soup.select('title'))

print(soup.select('a'))

(2)通过类名查找

print(soup.select('.mnav'))

(3)通过id查找

print(soup.select('#u1'))

(4)组合查找

print(soup.select('div .bri'))

(5)属性查找

print(soup.select('a[class="bri"]'))
print(soup.select('a[href="http://tieba.baidu.com"]'))

(6)获取内容

t_list = soup.select("title")
print(soup.select('title')[0].get_text())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值