Home > Software design >  How to click on a img id in HTML using Selenium and Python
How to click on a img id in HTML using Selenium and Python

Time:10-02

I am unable to find a way to click on a button that is an tag and not a . Here is the tag I am trying to click on. Btw that plus.png is used multiple times in the page.

<div class="col-md-12">
 <div class="text-center"><img src="./assets/img/plus.png" id="add_address"></div>
</div>

CodePudding user response:

use this xpath to click on it.

//img[@id='add_address']

Code trial 1 :

time.sleep(5)
driver.find_element_by_xpath("//img[@id='add_address']").click()

Code trial 2 :

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//img[@id='add_address']"))).click()

Code trial 3 :

time.sleep(5)
button = driver.find_element_by_xpath("//img[@id='add_address']")
driver.execute_script("arguments[0].click();", button)

Code trial 4 :

time.sleep(5)
button = driver.find_element_by_xpath("//img[@id='add_address']")
ActionChains(driver).move_to_element(button).click().perform()

Imports :

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

PS : Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

Not sure if we have unique ID, if ID is unique then you should give preference to ID not xpath.

  • Related