简体   繁体   English

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

[英]How to find whether an element is present or not in a class of html using selenium in python

I have to types of divisions of a same:我必须对相同的划分类型:

1) Which contain a division of a particular class (tile-freeCancellation) 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) Which do not have that class (tile-freeCancellation) 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>

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) ?有什么方法可以检查类的元素(tile-freeCancellation)是否存在于(类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我在这个程序中使用 python3 并使用函数 find_element_by_class_name 来查找主类的元素

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

My attempt- ternary operation(if) or if or helper function as by @W.我的尝试-三元操作(if)或 if 或辅助函数由@W 提供。 Cybriwsky赛布里夫斯基

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

In case of Nested element-eg select a div(motherelement) and then search inside it.在嵌套元素的情况下,例如选择一个 div(motherelement) 然后在其中搜索。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM