Myzel394
Myzel394

Reputation: 1317

Python BeautifulSoup select all elements whose attribute starts with

I want to select all elements who has at least one attribute that starts with "responsive-"

<div reponsive-devices="desktop"></div> #Select this
<ul responsive-os="android"></ul> # Select this
<div class="responsive-"></div> # DON'T select this

I already tried this: Can I select all elements whose attribute names (not values) start with a certain string? but it couldn't help me.

Does anyone have any idea?

Upvotes: 1

Views: 584

Answers (1)

Chankey Pathak
Chankey Pathak

Reputation: 21676

This is not straightforward but you can iterate over the tags and check if any of the attribute is starting with responsive.

See below code:

from bs4 import BeautifulSoup

data = '''<div responsive-devices="desktop"></div>
<ul responsive-os="android"></ul>
<div class="responsive-"></div>'''

soup = BeautifulSoup(''.join(data))

responsive_tag_list = soup.findAll(
                lambda tag:
                any([i.startswith('responsive-') for i in tag.attrs])
                )

print(responsive_tag_list)

Output:

[<div responsive-devices="desktop"></div>, <ul responsive-os="android"></ul>]

Upvotes: 1

Related Questions