How to find whether an element is present or not in a class of html using selenium in pythonAsk Question

问题:

I have to types of divisions of a same:

1) Which contain a division of a particular class (tile-freeCancellation)

<p class="col col-md-6 tile-duration">
  <span id="activityDuration183909" class="tile-activity-duration">
    <span class="icon icon-time" aria-hidden="true"></span>
    <span class="alt">Duration</span>
    2d+ 
  </span>
  <span id="activityFreeCancellation183909" class="tile-freeCancellation">
    <span id="offerFreeCancellationIcon4" class="icon icon-success" aria-hidden="true"></span>
    <span id="offerFreeCancellationText4" class="tile-free-cancel"> Free cancellation </span>
  </span>
</p>

2) Which do not have that class (tile-freeCancellation)

<p class="col col-md-6 tile-duration">
  <span id="activityDuration186022" class="tile-activity-duration">
    <span class="icon icon-time" aria-hidden="true"></span>
    <span class="alt">Duration</span>
    2d 
  </span>
</p>

Is there any way in which I can check if an element of a class (tile-freeCancellation) is present or not in the main element (of class tile-duration) ?

I am using python3 for this program and using the the function find_element_by_class_name for finding the element of main class

回答1:


My attempt- ternary operation(if) or if or helper function as by @W. Cybriwsky

if len(driver.find_elements_by_class_name("tile-freeCancellation"))>0:
    #do something
else:
    # do another

In case of Nested element-e.g. select a div(motherelement) and then search inside it.

if len(motherelement.find_elements_by_class_name("tile-freeCancellation"))>0:
    #do something
else:
    # do another

回答2:


The element objects that selenium returns have their own find_element_by_* methods which limit searches to their descendants, so you can do this like:

# Get a reference to both of the main elements
elements = driver.find_elements_by_class_name('tile-duration')

# helper function for checking presence of inner element
def free_cancel_descendants(element):
    return element.find_elements_by_class_name('tile-freeCancellation')

# use it, e.g. to filter the divs:
free_main_divs = [el for el in elements if free_cancel_descendants(el)]
标签: selenium webdriver
© 2014 TuiCode, Inc.