Using Selenium to Perform Drag and Drop Operations on an SVG Object

I am attempting to drag a specific Webelement and drop it inside an SVG "container" that contains four elements, which are represented by polygons. Each polygon is labeled as g[1], g[2], and so on.

Here is the HTML code of the container:

<div class="leaflet-overlay-pane"><img class="leaflet-image-layer leaflet- 
zoom-animated" src="/ik-conf/layout/Planos1544448485901.png" style="opacity: 
1; transform: translate3d(509px, 280px, 0px); width: 524px; height: 348px;">
<svg class="leaflet-zoom-animated" width="1472" height="855" viewBox="35 26 
1472 855" style="transform: translate3d(35px, 26px, 0px);">
<g><path stroke-linejoin="round" stroke-linecap="round" fill-rule="evenodd" 
stroke="#FF9900" stroke-opacity="0.5" stroke-width="5" fill="#FF9900" fill- 
opacity="0.2" class="leaflet-clickable" d="M714 300L709 586L529 591L533 
300z"></path></g>
<g><path stroke-linejoin="round" stroke-linecap="round" fill-rule="evenodd" 
stroke="#FF9900" stroke-opacity="0.5" stroke-width="5" fill="#FF9900" fill- 
opacity="0.2" class="leaflet-clickable" d="M1011 305L1009 585L802 589L797 
302z"></path></g>
<g><path stroke-linejoin="round" stroke-linecap="round" fill-rule="evenodd" 
stroke="#00FFD5" stroke-opacity="0.5" stroke-width="5" fill="#00FFD5" fill- 
opacity="0.2" class="leaflet-clickable" d="M690 444L688 554L544 552L544 
433z"></path></g>
<g><path stroke-linejoin="round" stroke-linecap="round" fill-rule="evenodd" 
stroke="#FFFFFF" stroke-opacity="0.5" stroke-width="5" fill="#FFFFFF" fill- 
opacity="0.2" class="leaflet-clickable" d="M989 321L987 444L816 435L816 
320z"></path></g>
</svg><div class="leaflet-draw-guides"></div></div>

Each of these polygons (G's) can be located by XPATH and/or CSS, however, I am encountering NoSuchElementException every time.

This is the code snippet I am executing:

public void dragAndDropPlanos(String nombre, WebElement poligono) {
    wait.until(ExpectedConditions.numberOfElementsToBe(By.xpath("//*[contains(text(),'" + nombre + "')]"), 1));
    WebElement element = driver.findElement(By.xpath("//*[contains(text(),'" + nombre + "')]"));
    js.executeScript("arguments[0].scrollIntoView(true);", element);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }
    WebElement element1 = driver.findElement(By.xpath("//*[contains(text(),'" + nombre + "')]"));
    wait.until(ExpectedConditions.visibilityOf(element1));
//        WebElement target = poligono; 
    wait.until(ExpectedConditions.visibilityOf(poligono));
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
    }
    WebElement element3 = driver.findElement(By.xpath("//*[contains(text(),'" + nombre + "')]"));
    (new Actions(driver)).dragAndDrop(element3, poligono).perform();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
    }
}

In the above code, I pass a string name as an argument, concatenate it with XPATH to locate the element for dragging, and also pass a webelement representing the polygon where I intend to drop the element. It seems like the SVG may exist in a different iframe, but after switching through iframes, I realized it is only within a div and accessible via xpath.

If anyone could shed some light on this issue, it would be greatly appreciated.
Thank you in advance!

Answer №1

It is possible that you have encountered incorrect WebElements due to overly broad conditions and potentially suspicious text.

  //*[contains(text(),'" + nombre + "')]

Firstly, if you are searching for visible text, this locator may not return anything as there is no text within the SVG. Secondly, consider narrowing down your search by using tag names before resorting to searching for any element with text.

   List<WebElement> elements = driver.findElements(By.tagName("g"));

In addition, even if the g element is found, some drivers (such as PhantomJS) may encounter difficulties manipulating it, requiring you to access internal elements like (path).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guaranteeing the sequential execution of JavaScript functions

For weeks, I've been struggling with a program that utilizes ajax post methods and dataTables. It has become clear to me that my understanding of how javascript operates is lacking. Below is the javascript code: $('#SaveTimeSheet').click(fu ...

In Vue(tify), transitions require children to have keys, but in this case, there are no tags present as children

Trying to implement a transition on a list using Vue and Vuetify, but encountering the error message vue.runtime.esm.js?2b0e:619 [Vue warn]: <transition-group> children must be keyed: <v-card> I attempted the Vuetify approach <v-fade-transi ...

Does utilizing a css selector in webdriver result in an error stating that another element would intercept the click action?

When it comes to the code below, I have opted for the first commented out option: driver.find_element_by_css_selector("div.show_hide:nth-child(7) > h5:ntchild(1)").click() I've also experimented with some other options: driver.find_element_by_xp ...

When attempting to start a session with a Chrome browser, the WebDriverManager gets stuck in a never-ending loop

After deciding to upgrade the automation infrastructure program, I made the choice to remove the Chrome driver exe from my project. In its place, I wanted to implement a new method that would reduce the need for manual updates whenever Chrome driver needs ...

Removing elements from an array of objects using specific values stored in another array - JavaScript

I'm currently working on implementing a reducer in redux that can delete multiple items from the state based on an array of values. Let's say I have the following array: const idArray = ["935", "933", "930"]; My goal is to remove objects that ...

Working with Angular's forEach method and handling null values

I'm encountering an issue where the array of selected devices is not getting the values when attempting to add multiple devices to a group. Can someone identify the problem or suggest an alternative method? I referred to http://www.dotnetawesome.com/2 ...

Tips for saving an image using Selenium?

from selenium import webdriver from selenium.webdriver import ActionChains def checkElementExistsByXpath(xpath): try: element = driver.find_element_by_xpath(xpath) return True except Exception as e: return False driver = w ...

Selenium grid can handle up to 4 to 5 simultaneous sessions

Currently, I am utilizing a Selenium grid with 3 allocated machines. Here is my configuration for the hub: { "port": 4444, "newSessionWaitTimeout": -1, "servlets": [], "prioritizer": "com.xxxx.xxxx.grid.xxxxxxx", "capabilityMatcher": "org.openqa ...

Detect if the user is using Internet Explorer and redirect them to a different

My web application is having trouble rendering in Internet Explorer. In the meantime, I would like to detect if the user is using IE and redirect them to a different page specifically for IE visitors. What is the best way to accomplish this? Should I use ...

Is it possible to create a sticky element that stays fixed to the window without using JavaScript?

Using position: sticky has been a game-changer for me. It resolves many issues without the need for JavaScript. However, I've encountered a roadblock. I am trying to create a sticky element that is nested inside multiple <div> elements. Since po ...

Save JSON data in an HTML document or vice versa

Hey there, the title of this post might seem a bit unclear but I couldn't think of another way to phrase it. So here's the dilemma: I have some data that is JSON encoded and stored in a .json file: {"foo":"bar", "bar":"foo", "far":"boo"} Additi ...

Error: Attempting to assign a value to 'onclick' property of null object [Chrome Extension]

window.onload = function() { document.getElementById('item_save').onclick = function() { var item_name = document.getElementById('item_name').value; var item_size = document.getElementById('item_size').value; v ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

What is causing the newly generated input tags to disappear from the page?

I'm having an issue where my code successfully creates new input tags based on user input, but they disappear shortly after being generated. What could be causing this to happen? <form> <input type='text' id='input' /> ...

Having difficulty choosing a dropdown option within a constantly changing webtable using Internet Explorer

I've been attempting to click on a dropdown within a webpage that's nested inside a dynamic webtable. Despite trying various methods such as driver.findelement, actions.movetoElement, javascript, Robot keypress, I haven't had any success in ...

Issue with Firefox causing problems with smooth scrolling Javascript on internal links

I recently created a one-page website using Bootstrap. The navigation menu items are internal links that point to different sections within the page, and I added some smooth scroll JavaScript for a more polished scrolling effect. While the website functio ...

Navigating to another webpage without closing the existing VB.Net Selenium Chrome window

Hello fellow forum members. I have a small issue with my code snippet below that uses selenium to open the Chrome web browser and navigate to a specific URL. When I click on Button1, it successfully opens a new Chrome window and directs me to . However, w ...

Using ng-pattern to validate that a text field does not conclude with a particular term

In this code snippet, I am attempting to prevent a textfield from ending with any of the specified letters in the $scope.pointPattern variable. $scope.pointPattern = /^(?!.*ess|ence|sports|riding?$)/; $scope.error = "not valid"; Upon executio ...

Update the displayed locations on Google Maps by fetching and displaying marker data

I am able to retrieve and display information from my MySQL table, but I need assistance with refreshing this data every 5 seconds using my current code. The data being shown is not extensive, just about 5 or 8 markers at a time. Below is the code I curren ...

Setting model value in Angular 2 and 4 from loop index

Is it possible to assign a model value from the current loop index? I've tried, but it doesn't seem to be working. Any suggestions on how to achieve this? Check out this link for my code <p *ngFor="let person of peoples; let i = index;"& ...