Friday, October 26, 2012

How to locate element in Html 'svg' tag in Selenium 2(Webdriver)


Sample svg code enbeded into Html code
 <html>  
 <head>  
 <title>automatethebox.blogspot.com</title>  
 </head>  
 <body>  
 <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="939" height="360">  
 <defs>  
 <g zIndex="10">  
 <tspan x="5.5">You</tspan>  
 </g>  
 <g zIndex="20">  
 <tspan x="5.5">Me</tspan>  
 </g>  
 <g zIndex="30">  
 <tspan x="5.5">None</tspan>  
 </g>  
 </svg>  
 </body>  
 </html>  
Selenium 2 (Webdriver) code to locate and intract with an svg element embeded into HTML 
Suppose in above given svg code three buttons are embeded into the svg.
Now we will be finding the button and be clicking on them using 'css locators'.Here we go....

Method 1
 // First of all find the 'svg' tag in the page and save it into as WebElement instance.  
 WebElement svgElement = driver.findElement(By.cssSelector("svg"));  
   
 // Get the Buttons with which we want to interact in a list  
 List<WebElement> gElements = svgElement.findElements(By.cssSelector("g"));  
   
 // Click on 'Me' Button  
 WebElement button = gElements.get(0).findElement(By.cssSelector("tspan");  
 button.click();  
   
 // Click on 'You' Button  
 WebElement button = gElements.get(1).findElement(By.cssSelector("tspan");  
 button.click();  
   
 // Click on 'None' Button  
 WebElement button = gElements.get(2).findElement(By.cssSelector("tspan");  
 button.click();  
Method 2
 // Locate buttons and save in the WebElement instances.  
 WebElement meButton = driver.findElement(By.cssSelector("//*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']//*[local-name()='tspan' and text()='Me']"));  
 WebElement youButton = driver.findElement(By.cssSelector("//*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']//*[local-name()='tspan' and text()='You']"));  
 WebElement noneButton = driver.findElement(By.cssSelector("//*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']//*[local-name()='tspan' and text()='None']"));  
   
 // Click on the buttons.  
 meButton.click();  
 youButton.click();  
 noneButton.click();  

3 comments:

lalit kumar said...

[img]http://s20.postimg.org/4n1fogigd/how_to_locate_element_in_svg_tag_in.png[/img]

Praveen Kumar said...

Valuable information thanks for sharing Selenium Online Training

ajay ak said...

Thanks for the useful information of software testing courses, give more updates on software testing development, First time I visit your blog really nice, I bookmark your blog here after a daily visit. Learn software testing course in Chennai

AWS Certified Solutions Architect Associate - AWS Introduction - Questions

All the Best !!! Show Result !! Try Again !! ×