day03BS4搜索文档树

本文介绍了如何使用Python的BeautifulSoup库解析HTML文档,包括查找特定标签、属性和文本的方法,以及使用正则表达式和列表过滤器进行高级搜索的技术。

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

'''
find:找第一个
find_all:找所有
标签查找与属性查找:

name 属性匹配
name 标签名
attrs 属性查找匹配
text 文本匹配
标签:
- 字符串过滤器 字符串全局匹配


- 正则过滤器
re模块匹配

- 列表过滤器
列表内的数据匹配

- bool过滤器
True匹配

- 方法过滤器
用于一些要的属性以及不需要的属性查找。

属性:
- class_
- id
'''
html_doc = """
<html><head><title>The Dormouse's story</title></head><body><p class="sister"><b>$37</b></p><p class="story" id="p">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" >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>
"""
from bs4 import BeautifulSoup
import re
soup=BeautifulSoup(html_doc,'lxml')
# name 标签名
# attrs 属性查找匹配
# text 文本匹配
#find与findall搜索文档

p=soup.find(name='div')
p_s=soup.find_all(name='p')

print(p)
print(p_s)
#name+attrs
p=soup.find(name='p',attrs={"id":"p"})
print(p)
#name+text
p=soup.find(name='title',text="The Dormouse's story")
print(p)
#name+attrs+text
p=soup.find(name='a',attrs={"class":"sister"},text="Elsie")
print(p)
'''
正则过滤器
re模块匹配
'''
#name
#根据re模块匹配带有a的节点
a=soup.find(name=re.compile('a'))
print(a)

a_s=soup.find_all(name=re.compile('a'))
print(a_s)
'''
列表过滤器
列表内的数据匹配
'''
print(soup.find(name=['a','p','html',re.compile('a')]))
print(soup.find_all(name=['a','p','html',re.compile('a')]))
'''
bool过滤器
True匹配
'''
print(soup.find(name=True,attrs={"id":Ture}))
'''
方法过滤器
用于一些要的属性以及不需要的属性查找
'''
def foo(tag):
    print(tag.name)
    if tag.name=='p'and tag.has_attr("id")and not tag.has_attr("class"):
        return tag

# print(soup.find_all(name=函数对象))
print(soup.find_all(name=foo))
'''
补充
'''
#id
a=soup.find(id='link2')
print(a)
#class
p=soup.find(class_='sister')
print(p)

 



转载于:https://www.cnblogs.com/changgeyimeng/p/11128505.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值