Введение в SVG
Самый распространенный векторный формат, который применяется для анимации в современном Интернете – Adobe (Macromedia) Flash . Яркие, интерактивные ролики, игры – автономные и распределенные, обучающие системы и видео – все это формат Flash , который по праву завоевал заслуженную популярность. Вместе с тем SVG очень похож на Flash . В табл. 1.1 приводится их сравнительная характеристика.
Свойство | SWF (Flash) | SVG |
---|---|---|
Открытый стандарт , спецификация | нет, Macromedia SWF Specification License (http://www.macromedia.com/software/flash/open/licensing/fileformat/) | да, World Wide Web Consortium (W3C) Specification (http://www.w3.org/TR/SVG/>) |
Тип данных | Двоичный | Основанный на тексте, может быть прочитан непосредственно. |
Тип MIME | application/x-shockwave-flash | image/ svg +xml |
Интерактивность. | Есть | Есть |
Сжатие | Есть, zlib | Есть, gzip |
Размер файлов | В общем случае трудно сказать, какой из файлов – SWF или SVG будет более компактным. Поскольку SWF файлы двоичные, то следует ожидать от них меньшего размера. С другой стороны формат SVG поддерживает gzip компрессию и конечные SVGZ файлы могут быть сравнимы по размеру (такие документы имеют расширение svgz). | |
Поддержка браузерами | Большинство браузеров, включая самый распространенный Internet Explorer 6, содержат встроенные плейеры. Размер Adobe Flash Player 9 составляет 1,21 Мб | Не поддерживается браузером Internet Explorer 6. Для отображения нужен плагин Adobe SVG Viewer 3.03, размер которого составляет 2,27 Мб |
Индексация поисковыми системами. | Поддерживается, при помощи специальных средств. | Поддерживается, причем описание и ключевые слова можно встраивать в сам SVG –документ. |
Поддержка графических фильтров | Поддерживаются начиная с flash player 8 | Есть |
Динамическая поддержка библиотек кода (PHP, XSLT , JSP ) | Есть | Есть |
Поддержка CSS, XSL , XPath | Труднореализуемо | Есть. |
Можно заметить, что SVG –формат практически ничем не уступает Flash , а кое в чем и превосходит Flash . Почему же тогда последний используется несравненно более широко? Основная причина ограниченности распространения SVG файлов – отсутствие программных пакетов, таких как Adobe (Macromedia) Flash или Swish, позволяющих быстро создавать анимацию при помощи визуальных средств. Компания Kiyut создала неплохой редактор Sketsa SVG Graphics Editor (http://www.kiyut.com/products/sketsa/index.html), но он скорее напоминает одну из графических программ – Adobe Illustrator или Corel Draw , чем комплексный пакет графики и программирования Adobe (Macromedia) Flash (рис. 1.3):
Имеются также редакторы SVG , создаваемые энтузиастами. Pilat (http://pilat.free.fr/dessin_loc/draw.svg) создал достаточно интересный редактор в формате SVG , доступный онлайн , но до Flash ему также далеко (рис. 1.4):
Одни из самых впечатляющих примеров использования SVG приложений расположены на сайте Adobe. Интерактивная диаграмма распределения численности населения по странам мира, с возможностью добавления величин и выбора типа графика (рис. 1.5)
Схема зданий – близнецов с возможностью навигации по этажам и просмотра схемы (рис. 1.6):
И, наконец, самый интересный пример – то, чего не может Flash ! Трехмерная структура химических соединений с возможностью управления в пространстве, масштабирования и выделения названий атомов как обычного текста (рис. 1.7):
Find SVG Element using XPath in Selenium Webdriver
XPath is a language for locating web elements in an XML document, including the HTML documents that make up a web page. In Selenium, XPath is one of the most widely used methods for finding elements on a web page, including SVG (Scalable Vector Graphics) elements.
SVG elements differ from regular HTML elements because they are created using XML, not HTML. Finding them in Selenium requires a different approach than finding HTML elements. This post will cover the steps to locate SVG elements in Selenium using XPath.
We will use our selenium playground website to automate the SVG elements – https://testkru.com/Elements/SVGelemnts.
With normal HTML elements, we can directly use the tags to find the elements in selenium. But if we try to do so with SVG elements, we might not get the desired results, as shown in the below image.
Here we used a simple “ //svg ” Xpath, and it didn’t find any matches.
Note: It would have worked if we had used something like an id for an SVG element. Like, If we had used driver.findElement(By.id(«svgText»)) , then the corresponding SVG element could have been found.
How to write XPath for SVG elements
What if no id or unique attribute was attached to the SVG element? Then how would we locate the SVG element in Selenium?
We can use the local-name() function to locate SVG elements in selenium.
Syntax of using local-name()
So, to find the SVG elements, we can use the “ //*[local-name()=’svg’] ” XPath, and it will locate all the SVG elements.
Note: The local-name() function is not only limited to the “svg” tag. It can be used with any tag like div, p, etc.
Code Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class CodekruTest < public static void main(String[] args) < // pass the path of the chromedriver location in the second argument System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://testkru.com/Elements/SVGelemnts"); // finding the SVG elements WebElement webElement = driver.findElement(By.xpath("//*[local-name()='svg']")); System.out.println(webElement.getText()); >>
findElement() returned the first matching element for the XPath passed in the arguments, and then we used the getText() method to print the text.
A point to remember
It is important to note that we should use * (star) while writing XPath for SVG elements. If we had written something like “ //div[local-name()=’svg’] “, then it wouldn’t have worked. So, traditional XPath(s) won’t work with SVG elements.
Using “and” with SVG elements
As we had seen in our previous example that when we used “ //*[local-name()=’svg’] ” XPath, it matched with 6 SVG elements, but what if you wanted a specific SVG element?
We can use “and” along with the local-name() function in that scenario.
//*[local-name()='svg' and @attribute_name = 'attribute_value']
It will locate SVG elements with a specific attribute’s value.
So, considering this, we can pinpoint the SVG element whose height attribute value equals 180 using the below XPath.
//*[local-name()='svg' and @height= '180']
How to locate the nested SVG elements?
We can similarly locate the nested SVG elements by using the below XPath.
This is it. We hope you have liked the article. If you have any doubts or concerns, please write to us in the comments or mail us at [email protected].