Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if an attribute is present in a tag in BeautifulSoup

I would like to get all the <script> tags in a document and then process each one based on the presence (or absence) of certain attributes.

E.g., for each <script> tag, if the attribute for is present do something; else if the attribute bar 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 <script> tags with the for attribute... but I lost the other ones (those without the for attribute).

like image 582
LB40 Avatar asked Feb 16 '11 10:02

LB40


People also ask

What is Find () method in BeautifulSoup?

find() method The find method is used for finding out the first tag with the specified name or id and returning an object of type bs4. Example: For instance, consider this simple HTML webpage having different paragraph tags.

Is Tag an object of BeautifulSoup?

A tag object in BeautifulSoup corresponds to an HTML or XML tag in the actual page or document. Tags contain lot of attributes and methods and two important features of a tag are its name and attributes.

What is Attrs in BeautifulSoup?

Extract attribute from an elementBeautifulSoup allows you to extract a single attribute from an element given its name just like how you would access a Python dictionary. For example, the following code snippet prints out the first author link from Quotes to Scrape page.


1 Answers

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'):         do_something()         
like image 182
Lucas S. Avatar answered Sep 18 '22 07:09

Lucas S.