Unable to locate SVG elements through xpath on Ken

2019-08-02 00:59发布

问题:

I did try some of xpaths but seems no luck.

I want to click on country and then graph , Given below screenshot :

Website URL is : https://demos.telerik.com/kendo-ui/bar-charts/column

I tried xpaths :

//text(text()='India')


 //g//text(text()='India')

回答1:

As the desired elements are SVG Elements you need to consider the namespace and induce WebDriverWait for the desired element to be clickable and to click on the first bar within the graph you can use the following solution:

  • Code Block:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    options = webdriver.ChromeOptions()
    options.add_argument("start-maximized")
    options.add_argument("disable-infobars")
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("https://demos.telerik.com/kendo-ui/bar-charts/column")
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='chart']//*[name()='svg']//*[name()='g']//*[text()='India']//following::*[name()='path']"))).click()
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='chart']//*[name()='svg']//*[name()='g'][contains(@clip-path, 'url')]//*[name()='path']"))).click()
    
  • Browser Snapshot:



回答2:

Hi you can click India with the following Xpath //*[text()='India']

This is a really helpful resource

I usually open chrome inspector and then hit cntrl+F to open up an interactive way to test my xpaths:

You can target the svgs by using their strokes, but note these may change often. example: //*[@d='M54.5 164.5 L 70.5 164.5 70.5 236.5 54.5 236.5Z' and @stroke='#03a9f4']



回答3:

The elements on chart are from SVG-namespace, so you cannot use common syntax to select those elements (you wouldn't be able to select element by its tag name, e.g. //svg or //path, etc)

You can try below to select text node with text "India":

//*[name()="text" and text()="India"]