如何使用Selenium和python查找不包含特定类名的元素 [英] How to find elements that do not include a certain class name with selenium and python

查看:974
本文介绍了如何使用Selenium和python查找不包含特定类名的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到所有包含某个类名的元素,但要跳过那些我正在搜索的元素之外还包含另一个类名的元素

I want to find all the elements that contain a certain class name but skip the ones the also contain another class name beside the one that i am searching for

我有元素<div class="examplenameA">和元素<div class="examplenameA examplenameB">

此刻我正在这样做以克服我的问题:

At the moment i am doing this to overcome my problem:

items = driver.find_elements_by_class_name('examplenameA')
for item in items:
    cname = item.get_attribute('class')
    if 'examplenameB' in cname:
        pass
    else:
        rest of code

我只想要具有类名examplenameA的元素,而我想跳过那些也包含examplenameB

I only want the elements that have the class name examplenameA and i want to skip the ones that also contain examplenameB

推荐答案

查找具有 class attribute examplenameA 的所有元素忽略具有 class attribute 作为 examplenameB 的那些,您可以使用以下解决方案:

To find all the elements with class attribute as examplenameA leaving out the ones with class attribute as examplenameB you can use the following solution:

  • css_selector:

items = driver.find_elements_by_css_selector("div.examplenameA:not(.examplenameB)")

  • xpath:

    items = driver.find_element_by_xpath("//div[contains(@class, 'examplenameA') and not(@class='examplenameB')]")
    

  • 这篇关于如何使用Selenium和python查找不包含特定类名的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆