Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

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

I have two cases where i want to scrape html tags with custom html attributes This is the example of the html. How do you scrape all the elements with the custom attribute "limit".

<div class="names" limit="10">Bar</div> 
<div id="30" limit="20">Foo</div> 
<li limit="x">Baz</li>

The second case is similar but with all the same html tags

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

My question is different than How to find tags with only certain attributes - BeautifulSoup because the latter targets attribute values with a specific tag whereas my question finds attributes only regardless of tag or value

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
# First case:
soup.find_all(attrs={"limit":True})

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

Reference:


If your attribute name doesn't collide with either Python keywords or soup.find_all named args, the syntax is simpler:

soup.find_all(id=True)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...