Home > database >  How to click on a path element within g tag using Python Selenium
How to click on a path element within g tag using Python Selenium

Time:07-26

I am trying to click path element with selenium python.

Code trials:

def find_the_place_path(self):
  # firstly I will get the all path tags
  all_place_in_path = self.driver.find_elements_by_tag_name("path")
  # title of my path tag is "gat: 3"
  for place in all_place_in_path:
    print(place.get_attribute('title'))
    if place.get_attribute('title') == "gat: 3":
      # this code id not worked for me
      place.click()

HTML snapshot:

enter image description here

CodePudding user response:

path is a svg element. use the following xpath to identify the element first and then click.

XPATH: //*[name()='path'][@title='gat: 3']

To click on dynamic element use WebDriverWait() and wait for element_to_be_clickable()

wait = WebDriverWait(driver, 10)

wait.until(EC.element_to_be_clickable((By.XPATH, "//*[name()='path'][@title='gat: 3']"))).click()

You need to import following libraries

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

CodePudding user response:

To click on the <path> element as it is within SVG namespace you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "svg g.coupe path[fill-rule='nonzero']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[name()='svg']//*[name()='g' and @class='coupe']//*[name()='path' and @fill-rule='nonzero']"))).click()
    
  • Note: You have to add the following imports :

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