最新消息:20210917 已从crifan.com换到crifan.org

【整理】用BeautifulSoup查找属性值未知的标签

BeautifulSoup crifan 8608浏览 0评论

【背景】

对于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});

就可以查找到对应的包含属性aria-lable的div标签了。

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

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

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

BeautifulSoup 3的中文版文档

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

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

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

4.完整代码为:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【整理】用BeautifulSoup查找属性值未知的标签
【整理】用BeautifulSoup查找属性值未知的标签
Author: Crifan Li Version: 2013-07-17 Contact: https://www.crifan.org/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去匹配。

转载请注明:在路上 » 【整理】用BeautifulSoup查找属性值未知的标签

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (3)

  1. 找了半天终于在你这看到答案了,多谢
    古凡6年前 (2017-12-02)回复
  2. 太棒了!!!多谢!!
    Shicheng9年前 (2014-12-20)回复
97 queries in 0.212 seconds, using 23.38MB memory