Home > database >  Selenium Python - unable to select by Xpath
Selenium Python - unable to select by Xpath

Time:10-18

I'm having an issue clicking an icon/link in a table. I've tried both find_element_by_xpath and find_elements_by_Xpath - no luck with either. I forced the wait as I was getting some issues with the element not being found.

I've highlighted the icon in the Table row, with the red box. in this image. Website

Also found the Xpath but can't seem to get it to work, the icon is clickable on the webpage. Xpath

My code is below:

driver.implicitly_wait(7)
tr = driver.find_element_by_xpath('//*[@id="AthleteTheme_wt6_block_wtMainContent_wt9_wtClassTable_ctl05_AthleteTheme_wt221_block_wtIconSvg_Svg"]/svg/use')

tr.click()

Thanks

CodePudding user response:

The Element is in an svg tag. And there is a different syntax for the same. Links to refer - Link1, Link2

To access svg tag elements the syntax would something like this:

//*[local-name()='svg']

As per the screen shot the xpath for the Elements would be:

//span[@id="AthleteTheme_wt6_block_wtMainContent_wt9_wtClassTable_ctl05_AthleteTheme_wt221_block_wtIconSvg_Svg"]/*[local-name()='svg']/*[local-name()='use']

CodePudding user response:

You can not directly use // to locate an SVG element. They are one of the special tags.

Always use //*[name()='svg'] or //*[local-name()='svg'] to locate them.

Based on the HTML that you've shared, Please use the below xpath :

//a[@class='svgContainer']//child::span//*[name()='svg' and starts-with(@id,'AthleteTheme')]//*[name()='use']

** 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.

Code trial 1 :

time.sleep(5)
driver.find_element_by_xpath("//a[@class='svgContainer']//child::span//*[name()='svg' and starts-with(@id,'AthleteTheme')]//*[name()='use']").click()

Code trial 2 :

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='svgContainer']//child::span//*[name()='svg' and starts-with(@id,'AthleteTheme')]//*[name()='use']"))).click()

Code trial 3 :

time.sleep(5)
button = driver.find_element_by_xpath("//a[@class='svgContainer']//child::span//*[name()='svg' and starts-with(@id,'AthleteTheme')]//*[name()='use']")
driver.execute_script("arguments[0].click();", button)

Code trial 4 :

time.sleep(5)
button = driver.find_element_by_xpath("//a[@class='svgContainer']//child::span//*[name()='svg' and starts-with(@id,'AthleteTheme')]//*[name()='use']")
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
  • Related