beautifulsoup4函数使用学习

beautifulsoup 用于提取抓取的html 字符串的标签

官网文档上的函数丰富,从上边找到的东西

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-parents-and-find-parent

1四类对象

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

  • Tag             
  • NavigableString
  • BeautifulSoup
  • Comment

2函数


find_all()
find()
find_parents() , find_parent()
find_next_siblings() ,find_next_sibling()
find_previous_siblings() ,find_previous_sibling()
find_all_next() ,find_next()
find_all_previous() , find_previous()

find(name,attrs,recursive,text,**wargs)

这些参数相当于过滤器一样可以进行筛选处理。

不同的参数过滤可以应用到以下情况:


一下查找方法可以组合查找

  • 查找标签,基于name参数
  • 查找文本,基于text参数
  • 基于正则表达式的查找
  • 查找标签的属性,基于attrs参数
  • 基于函数的查找
    html_doc = """
    <html><head><title>The Dormouse's story</title></head>
    <body>
    <p class="title"><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>
    """
    
    soup=BeautifulSoup(html_doc,'html.parser',from_encoding='utf-8')
基于标签 和 属性查找

      

link_node = soup.find('a',href='http://example.com/tillie')
  其中class为python关键字,关于class查找

查找class=‘mark’可以写成


1

link_node = soup.find(class_=mark)

2

link_node = soup.find(attrs={'class':'mark'}) 
其中方法2也可以作为查找其他跟python关键字或者命名规则有冲突的属性查找

基于文本查找

link_node = soup.find(text="plants")  

基于标签 和正则查找

link_node = soup.find('a',href=re.compile(r"lac"))

基于函数查找
def id_text_de(tag):
   return tag.name=='a' and tag.get_text()=='Elsie'
link_node = soup.find(id_text_de)

 find_all(name,attrs, recursive, string, limit, **kwargs)

find_all
就多了一个limit  
跟数据库那个limit差不多

其他查找父子兄弟节点函数


相当于find缩小了查询范围,用法基本一致

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值