Home > Mobile >  How to click on an image (not button) using Selenium
How to click on an image (not button) using Selenium

Time:04-28

Before this, I have automated a login into the website howe page. I was stuck trying to make it so that it clicks on the image to navigate to another webpage.

shop_button = driver.find_element(By.XPATH, "/html/body/footer/div/div[2]/a/img")

shop_button.click()

This is the code for the image hyperlink

CodePudding user response:

You want to redirect to another webpage by clicking on a image. According to the code snippet, I can see that Image tag is inside the tag, you can click on that. Can you try this ?

shop_button = driver.find_element(By.XPATH,"/html/body/footer/div/div[2]/a")

shop_button.click()

Do let me know if this works.

CodePudding user response:

You can use the below xpath

//p[text()='Shop']//preceding-sibling::img

this should locate the img node, however p tag which has Shop as a text has to be unique in nature.

If it's unique, you can click on it like:

Code trial 1:

time.sleep(5)
driver.find_element(By.XPATH, "//p[text()='Shop']//preceding-sibling::img").click()

Code trial 2:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//p[text()='Shop']//preceding-sibling::img"))).click()

Imports:

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

PS: time.sleep(5) is just for visualization purpose, you should not use it ideally if code 2 works fine.

  • Related