针对python爬虫bs4(BeautifulSoup)库的基础问题

本文介绍如何使用Python的BeautifulSoup库解析HTML文档。通过实例演示了文档解析过程,包括导入库、获取网页内容、基本使用方法等。展示了如何查找特定标签、获取属性和文本内容,以及使用find和select进行高级搜索。

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

bs4(BeautifulSoup)库的基本使用

 

1.导入模块

from bs4 import BeautifulSoup

2.解析获取到的网页内容

文档被转换成Unicode,并且HTML的实例都被转换成Unicode编码。

可以打印soup对象的内容,格式化输出:print soup.prettify()

url_str = getHTMLText(url)
soup = BeautifulSoup(url_str,'html.parser')

3.基本使用方法

bs4 将复杂的HTML文档转换成一个复杂的树形结构,每个节点都是python的对象。

根据标签查找(type:bs4_obj)

head = soup.head
"""
<head>
 <meta content="text/html;charset=utf-8" http-equiv="content-type"/>
 <meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
 <meta content="always" name="referrer"/>
 <link href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css"/>
 <title>
  百度一下,你就知道
 </title>
</head>
"""

获取属性

title = head.title # 在soup中获取第一个符合要求的标记
# <title>百度一下,你就知道</title>
title_str = name.string # 获取标签内部的文字
# 百度一下,你就知道

meta = head.meta
# <meta content="text/html;charset=utf-8" http-equiv="content-type"/>
content = meta.get('content') # 获取meta中第一个属性
content = meta['content']
# text/html;charset=utf-8
content = meta.attrs # 获取meta中所有属性
# {'http-equiv': 'content-type', 'content': 'text/html;charset=utf-8'}
meta.name = 'hi' # 修改标签的name
meta['content'] = 'hello world' # 修改标签的属性和内容
print(meta)
# <hi content="hello world" http-equiv="content-type"/>

获取文本内容

content = head.contents # 返回以head下各标签为元素的列表
"""
[<meta content="text/html;charset=utf-8" http-equiv="content-type"/>, <meta content="IE=Edge" http-equiv="X-UA-Compatible"/>, <meta content="always" name="referrer"/>, <link href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css"/>, <title>百度一下,你就知道</title>]
"""
print(content[0])
# <meta content="text/html;charset=utf-8" http-equiv="content-type"/>
text = head.get_text() # 获取head标签内部的文字
# 百度一下,你就知道

print(type(head.title.string)) # bs4.element.NavigableString
if type(head.title.string)== bs4.element.NavigableString: # 过滤注释内容
    print('这是注释内容')
else:
    print('这不是注释')

获取子孙节点(tpye:generator)

descendants = soup.p.descendants

find&&find_all查找

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

soup.find('a')
soup.find('a',title='hhh')
soup.find('a',id='',class_='')

soup.find_all('a') # 查找所有<a>标签
soup.find(id=True) # 查找所有包含id属性的标签
soup.find_all(limit=2) # 限定查找的返回数量
soup.find_all(['a','p']) # 查找所有<a>标签和<b>标签


str(soup.find_all('a',class_='title')[0]) # 注意因为class为关键字,所以用'class_'代替
soup.find_all(attrs = {'data-role':'goto-input'}) # '-'不能直接用作属性名,需用字典括起来

select选择(type:list)

soup.select('.main > ul > li > a')[0].string
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值