问题
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