How to find if there is an element in a div?

Viewed 41

I have a list of posts and some of them has reactions, some not. I want to extract the number of reactions of each posts and the problem is that those who doesn't have, there is no HTML code.

I tried to debug using print.

print(len(driver.find_elements_by_xpath("//div[@class='occludable-update ember-view']")))
-----
Output: 4 - This is good, because I have 4 divs
print(len(driver.find_elements_by_xpath("//span[@class='v-align-middle social-details-social-counts__reactions-count']"))
----
Output:2 - This is good, because I have 2 posts that got reactions

When I tried to find if a posts got reactions,

print(len(driver.find_elements_by_xpath("//div[@class='occludable-update ember-view']")[1].find_elements_by_xpath("//span[@class='v-align-middle social-details-social-counts__reactions-count']")))
----
Output: 2 - Why? Because the second div is empty...

HTML CODE

<div class="occludable-update ember-view">
  <ul class="social-details-social-counts ">
   <li class="social-details-social-counts__reactions social-details-social-counts__item ">
    <button class="social-details-social-counts__count-valuet " aria-label="1 Reaction’ post" type="button">
       <img class="reactions-icon social-detail">
       <span aria-hidden="true" class="v-align-middle social-details-social-counts__reactions-count">3</span>
    </button>
</li></ul>
</div>

<div class="occludable-update ember-view"> this div has no reaction </div>

<div class="occludable-update ember-view"> this div has no reaction </div>

<div class="occludable-update ember-view">
  <ul class="social-details-social-counts ">
   <li class="social-details-social-counts__reactions social-details-social-counts__item ">
    <button class="social-details-social-counts__count-valuet " aria-label="1 Reaction’ post" type="button">
       <img class="reactions-icon social-detail">
       <span aria-hidden="true" class="v-align-middle social-details-social-counts__reactions-count">3</span>
    </button>
</li></ul>
</div>
2 Answers

I found the problem. After better documenting myself, I found out that for sub-elements is used .// instead of //

print(len(driver.find_elements_by_xpath("//div[@class='occludable-update ember-view']")[1].find_elements_by_xpath(".//span[@class='v-align-middle social-details-social-counts__reactions-count']")))

to locate the continuation element, use .

try below :

driver.find_elements_by_xpath("//div[@class='occludable-update ember-view']")[1].find_elements_by_xpath(".//descendant::span[@class='v-align-middle social-details-social-counts__reactions-count']")
Related