How to find elements that do not include a certain class name with selenium and python

橙三吉。 提交于 2020-08-02 16:22:56

问题


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

I have the element <div class="examplenameA"> and the element <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

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


回答1:


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')]")
    



回答2:


You can use xpath in this case. So as per your example you need to use something like driver.find_elements_by_xpath('//div[@class='examplenameA'). This will give you only the elements whose class is examplenameA

So how xpath works is : Xpath=//tagname[@attribute='value']

Hence the class is considered as the attribute & xpath will try to match the exact given value, in this case examplenameA, so <div class="examplenameA examplenameB"> will be ignored

In case of find_elements_by_class_name method, it will try to match the element which has the class as examplenameA, so the <div class="examplenameA examplenameB"> will also be matched

Hope this helps



来源:https://stackoverflow.com/questions/54267038/how-to-find-elements-that-do-not-include-a-certain-class-name-with-selenium-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!