Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find elements that do not include a certain class name with selenium and 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

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

like image 845
Rius2 Avatar asked Mar 05 '23 16:03

Rius2


2 Answers

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')]")
    
like image 179
undetected Selenium Avatar answered Apr 05 '23 22:04

undetected Selenium


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

like image 36
SnR Avatar answered Apr 05 '23 22:04

SnR