如何使用Beautiful Soup查找具有自定义html属性的所有元素?

Dap*_*Dap 12 python beautifulsoup

我有两种情况,我想用自定义html属性刮取html这是html的例子.如何使用自定义属性"限制"清除所有元素.

<div class="names" limit="10">Bar</div> 
<div id="30" limit="20">Foo</div> 
<li limit="x">Baz</li>
Run Code Online (Sandbox Code Playgroud)

第二种情况类似,但所有相同的html标签

<div class="names" limit="10">Bar</div> 
<div class="names" limit="20">Bar</div> 
<div class="names" limit="30">Bar</div> 
Run Code Online (Sandbox Code Playgroud)

我的问题与如何找到只有某些属性的标签不同- BeautifulSoup,因为后者使用特定标签定位属性值,而我的问题仅在标记或值的情况下查找目标属性

Rob*_*obᵩ 30

# First case:
soup.find_all(attrs={"limit":True})

# Second case:
soup.find_all("div", attrs={"limit":True})
Run Code Online (Sandbox Code Playgroud)

参考:


如果您的属性名称不与Python关键字或soup.find_all命名args 冲突,则语法更简单:

soup.find_all(id=True)
Run Code Online (Sandbox Code Playgroud)

  • 更酷:`soup.find_all(attrs = {"limit":lambda x:x和x.isdigit()以及5 <int(x)<15}) (9认同)
  • 酷不知道它可以支持`attribs = True` (3认同)