Title: Checking for duplicate tags using Beautifulsoup
Tags: python
Question: I have a html file:
<html&gt;
<html&gt;
</html&gt;
</html&gt;
And I am trying to read this file using beautifulsoup in my test.py file , where i am testing for any duplicate html tags. I have below assert condition which check whether a html tag exists or not but do not have any condition to check whether there are duplicate html tags in a single file.
def testing(self):
try:
assert self.soup.find('html') != None
except AssertionError, e:
raise Exception("HTML Tag is missing!")
How can I include this in the test?

Here is the accepted answer: Specify an html.parser, find all html tags and check how many have you found.
Here's an example:
from bs4 import BeautifulSoup
invalid = """<html&gt;
<html&gt;
</html&gt;
</html&gt;"""
soup = BeautifulSoup(invalid, 'html.parser')
print len(soup.find_all("html"))  # prints 2
valid = """<html&gt;
</html&gt;"""
soup = BeautifulSoup(valid, 'html.parser')
print len(soup.find_all("html"))  # prints 1
In your test it would be:
assert len(self.soup.find_all('html')) == 1
Also, instead of using assert in this case, better use unittest's self.assertEqual(): it has a msg argument which will help you make your test more readable and pythonic:
self.assertEqual(len(self.soup.find_all('html')), 1, msg="HTML Tag is missing!")

Here is another answer: assert len(self.soup.findAll('html', recursive=False)) == 1 should work.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:03/01/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python>', 'Title': 'Checking for duplicate tags using Beautifulsoup', 'ViewCount': 374, 'id': 22108760, 'user_AboutMe': '', 'user_AccountId': 4101452.0, 'user_DisplayName': 'Jusrock', 'user_Reputation': 21.0, 'user_Views': 5.0, 'user_id': 3366889.0}}