Skip to content
Advertisement

Find elements by class name with Selenium in Python

<div class="innerImageOuterWrapper">
  <div class="innerImageWrapper editlink" id="imageGridWrapper_15961315" ximgid="23232323" onclick="displayEditImageBox('IMSIMAGE:ASDASD', 233232, 'new')" style="background: transparent url(&quot;https://xsad.com/xsd.jpg;) center center / cover no-repeat;">
    <img src="https://xsad.com/xsd.jpg" class="thumbnail scaleimg" id="imageGridimage_15961315" style="display: none;" wfd-invisible="true">
  </div>
  <div class="innerImageWrapper editlink" id="imageGridWrapper_15961314" ximgid="15961314" onclick="displayEditImageBox('IMSIMAGE:ASDASD23', 15961314, 'new')" style="background: transparent url(&quot;https://xsad.com/xsd.jpg&quot;) center center / cover no-repeat;">
    <img src="https://xsad.com/xsdsd.jpg" class="thumbnail scaleimg" id="imageGridimage_15961314" style="display: none;" wfd-invisible="true">
  </div>
</div>

I want to click on elements whose class is “innerImageWrapper editlink”.

I use this code

driver.find_elements(by=By.CLASS_NAME, value="innerImageWrapper editlink").click()

but it’s not working.

driver.find_element(by=By.XPATH,
                                value='//*[@id="imageGridWrapper_15961314"').click()

it’s working. but I dont want use xpath. I want use class name

Advertisement

Answer

By.CLASS_NAME receives single value while here you trying to pass 2 values: innerImageWrapper and editlink. To locate element by 2 class names you can use CSS Selector or XPath, but not CLASS_NAME.
So, you can use one of the following:

driver.find_element(By.CSS_SELECTOR, ".innerImageWrapper.editlink").click()

or

driver.find_element(By.XPATH, "//*[@class='innerImageWrapper editlink]").click()

Also, find_elements returns a list of web elements, you can not apply click() on it.
You should use find_element if you want to click on single element or if you want to click on multiple elements you need to iterate over the list of elements and click each one of them, as following:

elements = driver.find_elements(By.CSS_SELECTOR, ".innerImageWrapper.editlink")
for element in elements:
    element.click()
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement