TigerJ
TigerJ

Reputation: 87

How to click on element in Selenium python?

I'm new in Selenium and Python. I have the following code:

<div class="Product_ImageWrapper__3W7pX">
        <span class=" lazy-load-image-background opacity lazy-load-image-loaded" style="color: 
         transparent; display: inline-block; height: 100%; width: 100%;">
            <img class="Product_Image__1sMZc" src="xxx.jpg" alt="photo" height="100%" 
             width="100%"></span></div> 

What I'm trying to do is click on this image. There is always message:

Message: no such element: Unable to locate element:......

I tried:

driver.find_element_by_xpath('//span[img/@src="xxx.jpg"]').click()

or just by the name of the class but it doesn't work. Please help.

Upvotes: 1

Views: 132

Answers (2)

Justin Lambert
Justin Lambert

Reputation: 978

Please use following xpath "//img[@src='xxx.jpg']

Before to click you should wait for that element

Upvotes: 1

Aleksander Ikleiw
Aleksander Ikleiw

Reputation: 2675

Try the execute() function. It executes the code directly in the JavaScript Console.

driver.execute("document.getElementsByClassName(' lazy-load-image-background opacity lazy-load-image-loaded')[0].click()")

IF that did not work out, There is a second method using the WebdriverWait().

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(self.webdriver, 60).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'span[class=" lazy-load-image-background opacity lazy-load-image-loaded"]')))

Upvotes: 2

Related Questions