Home > OS >  Find elements by class name with Selenium in Python
Find elements by class name with Selenium in Python

Time:01-04

<div >
  <div  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"  id="imageGridimage_15961315" style="display: none;" wfd-invisible="true">
  </div>
  <div  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"  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

CodePudding user response:

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()
  • Related