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.
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
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"))
<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.
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
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"))