如何使用 Beautiful Soup 查找具有自定义 html 属性的所有元素,而不考虑 html 标签?

How to find all elements with a custom html attribute regardless of html tag using Beautiful Soup?

我有两种情况需要使用自定义 html 属性来抓取 html 标签 这是html的例子。如何使用自定义属性 "limit".

抓取所有元素
<div class="names" limit="10">Bar</div> 
<div id="30" limit="20">Foo</div> 
<li limit="x">Baz</li>

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

<div class="names" limit="10">Bar</div> 
<div class="names" limit="20">Bar</div> 
<div class="names" limit="30">Bar</div> 

我的问题与 How to find tags with only certain attributes - BeautifulSoup 不同,因为后者针对具有特定标签的属性值,而我的问题只查找属性,而不考虑标签或值

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

# Second case:
soup.find_all("div", attrs={"limit":True})

参考:


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

soup.find_all(id=True)