BeautifulSoup 用法 标签属性值不确定时用法

原文地址

【背景】

对于Python中的BeautifulSoup,之前用其去查找

<div aria-lable="xxx">

之类的标签,xxx的内容未知(可变)的前提下

想要查找到对应的此div标签,之前不知道如何实现。

因为如果写成:

sopu.findAll("div", attrs={"aria-lable": "xxx"});

则xxx必须写出来,如果不写出来属性值,也就没法用上attrs了,就没法实现此处查找特性属性值的标签了。

【解决过程】

1.后来看到:

关于正则表达式

针对:

<div aria-label="5星, 747 份评分" class="rating" role="img" tabindex="-1">
 <div>
  <span class="rating-star">
  </span>
  <span class="rating-star">
  </span>
  <span class="rating-star">
  </span>
  <span class="rating-star">
  </span>
  <span class="rating-star">
  </span>
 </div>
 <span class="rating-count">
  747 份评分
 </span>
</div>

可以通过:

soup.findAll("div", attrs={"aria-lable": True});

去查找到属性包含aria-lable的div标签的。

2.所以,对于上面的,之前不知道如何处理:

用BeautifulSoup查找未知属性值,但是已知属性的名字的标签

则此处,就可以针对:

<div aria-lable="xxx">

去用:

sopu.findAll("div", attrs={"aria-lable": True});

3. 后来就想到了,再去看看,在之前的:

【教程】BeautifulSoup中使用正则表达式去搜索多种可能的关键字

中提到的,bs的官网文档:

BeautifulSoup 3的中文版文档

然后,找了半天,好不容易,才找到,相关的解释:

特殊值True和None更让人感兴趣。 True匹配给定属性为任意值的标签,None匹配那些给定的属性值为空的标签。

所以,以后知道了,如果对于属性值之类的东西,是任意值,不确定的值的话,则都是用True。

4.完整代码为:

#!/usr/bin/python
#conding=utf-8
"""
Function:
【整理】用BeautifulSoup查找属性值未知的标签
http://www.crifan.com/python_use_beautifulsoup_find_tag_with_unknown_attribute_value/

Author:     Crifan Li
Version:    2013-07-17
Contact:    http://www.crifan.com/about/me/
"""

from BeautifulSoup import BeautifulSoup;

def beautifulsoup_tag_attr_unknown():
    """
        demo BeautifulSoup find the tag which attribute value unknown
    """
    html = """<div aria-label="5星, 747 份评分" class="rating" role="img" tabindex="-1">
 <div>
  <span class="rating-star">
  </span>
  <span class="rating-star">
  </span>
  <span class="rating-star">
  </span>
  <span class="rating-star">
  </span>
  <span class="rating-star">
  </span>
 </div>
 <span class="rating-count">
  747 份评分
 </span>
</div>""";
    soup = BeautifulSoup(html);

    foundDiv = soup.find(name="div", attrs={"aria-label":True});
    #print "foundDiv=",foundDiv;
    attrVal = foundDiv['aria-label'];
    print "attrVal=",attrVal; #attrVal= 5星, 747 份评分

if __name__ == "__main__":
    beautifulsoup_tag_attr_unknown();

【总结】

BeautifulSoup中,想要匹配:

<tag attr1="xxx">

则用:

sopu.find(name="tag", attrs={"attr1": True});

 

引申:

如果以后,在使用BeautifulSoup时,遇到类似的,想要匹配,未知的,任意的值,则应该,都可以用True去匹配。

*注: 仅作为个人笔记只用, 如有不妥,还望指正。


欢迎关注 [懒人漫说] 公众号,分享Java、Android、C/C++ 技术,
包括基础、自己遇到的问题解决过程。
在这里插入图片描述
当然如果关注并留言问题的话,我们力所能及的话会帮你解决并回复哟。我们和你一样,是正在成长的程序员,我们也会分享自己的成长路上的感想,希望可以和你一起努力成长。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值