如何在python中使用selenium在html类中查找元素是否存在

时间:2015-11-01 07:18:46

标签: python selenium webdriver

我必须使用相同类型的分区:

1)其中包含特定类的一个分区(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)哪个没有该类(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>

有没有办法可以检查主要元素(类tile-duration)中是否存在类(tile-freeCancellation)的元素?

我在这个程序中使用python3并使用函数find_element_by_class_name来查找主类的元素

2 个答案:

答案 0 :(得分:1)

selenium返回的元素对象有自己的find_element_by_ *方法,这些方法将搜索限制在后代,所以你可以这样做:

# 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)]

答案 1 :(得分:1)

我的尝试三元操作(如果)或者是@W的辅助函数。 Cybriwsky

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

在嵌套元素的情况下 - 例如。选择一个div(motherelement),然后在里面搜索。

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