LB40 LB40 - 1 year ago 114
Python Question

Test if an attribute is present in a tag in BeautifulSoup

I would like to get all the

tags in a document and then process each one based on the presence (or absence) of certain attributes.

E.g., for each
tag, if the attribute
is present do something; else if the attribute
is present do something else.

Here is what I am doing currently:

outputDoc = BeautifulSoup(''.join(output))
scriptTags = outputDoc.findAll('script', attrs = {'for' : True})

But this way I filter all the
tags with the
attribute... but I lost the other ones (those without the

Answer Source

If i understand well, you just want all the script tags, and then check for some attributes in them?

scriptTags = outputDoc.findAll('script')
for script in scriptTags:
    if script.has_attr('some_attribute'):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download