selenium python count the number of p tag

Question:

<div class="some_class">
   <p>...</p>
   <p>...</p>
   <p>...</p>
   <p>...</p>
</div>

How can I count the number of p tag inside the div?
The p tag is empty without any class or id or anything else.

Asked By: Tuan Le

||

Answers:

If the above html is stored in a string you could use count() to count the occurrence’s of <p>.

string = '''
<div class="some_class">
   <p>...</p>
   <p>...</p>
   <p>...</p>
   <p>...</p>
</div>
'''

string.count('<p>')
#4

However, in the case a tag is not closed, it would include the unclosed tag in the count.

To count the total number of complete <p> tags, you could use re.findall() and len().

import re

re.findall(r'<p>.*?</p>', string)
#['<p>...</p>', '<p>...</p>', '<p>...</p>', '<p>...</p>']

len(re.findall(r'<p>.*?</p>', string))
#4
Answered By: PacketLoss

Oh I missed it. Thanks @frianH for highlighting

Try below snippet:

parentDiv = driver.find_element_by_class_name("some_class")
count  = len(parentDiv.find_elements_by_tag_name("p"))
Answered By: Ambrish Pathak
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.