Choosing the element g within the SVG element using Selenium

I'm new to using selenium and I've hit a roadblock that I could really use some expert advice on.

Here is the HTML code I'm working with:

<div id='d3_tree'>
   <svg>
     <g transform="translate(20,50)>
        <g class='node'>
        </g> 
        <g class='node pe_node'>
        </g>
        <g class='node pe_node'>
        </g> 
     </g>
   </svg>
</div>

I need to target all the <g> elements with the class pe_node and trigger a context menu on them. Here's what I've tried:

node = self.driver.find_elements(By.XPATH, "//div[@id='d3_tree']/'svg']/g")

I then learned that SVG elements cannot be selected directly, so I attempted these alternatives:

nodes = self.driver.find_elements(By.XPATH, "//div[@id='d3_tree']/*[name()='svg']/g")

and

nodes = self.driver.find_elements(By.XPATH, "//div[@id='d3_tree']/*[local-name()='svg']/g")

Unfortunately, none of these solutions are yielding the results I expected, as I am getting an empty list ([]) in return.

If anyone can provide guidance on how to specifically select the <g> elements with the class pe_node within the SVG, I would greatly appreciate it.

Thank you for any assistance.

Answer №1

Almost there, this solution should do the trick:

nodes = self.driver.find_elements(By.XPATH, "//div[@id='d3_tree']/*[name()='svg']/*[name()='g']")

To reference elements inside 'svg', use `/*[name()='']

In this case, you can simplify it with:

nodes = self.driver.find_elements(By.XPATH, "//div[@id='d3_tree']/*/*[name()='g']")

Answer №2

This Xpath expression should be effective:

//div[@id='d3_tree']//g[contains(@class, 'pe_node')]

Answer №3

Is there a way to target the <svg> element without using the tagName?

element = driver.findElement(By.tagName("svg"))
additionalElements = element.findElements(By.Xpath("./g[contains(@class, 'pe_node')]")

Answer №4

If you're not sure what language you are working with, give this code snippet a shot. The Selenium script provided below may come in handy for your task. It retrieves all elements within the svg tag that have the class "node pe_node".

element = self.driver.find_element(By.XPATH, "//div[@id='d3_tree']/svg]")
elements = element.find_elements(By.XPATH,"//g[@class='node pe_node']")

Answer №5

A possible way to express this is:

//div[@id='d3_tree']/*[name()='svg']/*[name()='g' and @class='node pe_node']/*[name()='g'][2]

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

An Axios error message indicates ERR_NETWORK and ERR_EMPTY_RESPONSE

When I initiate a Patch Request from the frontend, it takes approximately 30-40 seconds for the backend to resolve. const handleSendClick = (data: any) => { const requiredLanguages = Array.isArray(data.required_languages) ? data.required_langu ...

Will the useEffect hook re-run whenever the component renders if it includes props in its dependency array?

According to the React documentation on useEffect, it is recommended to include props in the dependency array of useEffect: import { useEffect } from 'react'; import { createConnection } from './chat.js'; function ChatRoom({ roomId }) ...

The Firefox extension is unable to activate any click events

Currently, I am developing a Firefox add-on with the goal of automatically filling in login form fields and submitting the login. For each website, I have access to various identifiers such as ids, classes or xpath, depending on what is provided by the web ...

Prevent Alert Pop-ups from Occurring on Page Exit in Python using Selenium

Utilizing Python 3 and Chromedriver. Imagine an automated python script navigating the web, gathering information from various sources. If any of these websites triggers an "Are you sure you wanna leave this page?" alert. Important phrase: any (in a ran ...

Aligning the canvas resolution to match the video resolution for superimposition purposes

Within a div, I have both a canvas and a video element: <div id="videos"> <canvas id="my-canvas"></canvas> <video id="remote-video" autoplay></video> </div> Below is the css styling for both elements: #my-canv ...

Despite having the necessary jar file, the connection between Java and the MySQL database still cannot be

import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DbManager { public static Connection conn = null; // mysql public static void setMysqlDbConnection() throws SQLException, ClassNotFoundException ...

How to use Python Selenium to target elements with closely matching class names

As I work on scraping a website using Selenium in Python, I came across a question that has only been answered in HTML format: how do I select certain elements with a specific class name? <span ng-if="evento.quota>=100" class="ng-bindi ...

What is causing the loss of context for 'this' in the latest Angular 1.5 components?

Encountering a strange issue with the new components. Previously, in version 1.4 directive, we had this block of code... (function () { 'use strict'; angular.module('app.board').directive('dcCb', dcClipboardCopy); funct ...

Tips for creating a striped background color on your Blogger blog's homepage

Currently, I am personalizing the default theme on Blogger called Simple Dark, but I have hit a roadblock when it comes to creating a striped background color for the posts on the homepage. Here is a glimpse of how my blog currently appears, and here is ...

Decoding information from the twitchapi

I have recently embarked on a coding journey to create a Twitch bot, and my next endeavor is to establish a point system based on active viewers. To achieve this, I require the ability to extract viewer data from Twitch's API in JSON format. However, ...

"Using Jquery to Extract Content from CKEditor: A Step-by-Step Guide

I have integrated the CKEditor control in my asp.net project, here is an example: <CKEditor:CKEditorControl ID="CKEditor1" BasePath="/ckeditor/" runat="server"> Can anyone recommend a method to retrieve the content from this editor using jquery? ...

An unspecified number of Ajax requests being made within a loop

Here is the dilemma I'm facing, despite trying different recommendations from StackOverflow: Situation: I am utilizing the Gitlab API to display all the "issues" in the bug tracker of a specific project on the system. Challenges: Everything wor ...

Creating a semicircle shape using three.js extrusion

I am trying to create half of an extruded circle using this code, but it only draws a cube. How can I modify it to achieve the desired shape? // Drawing half of an extruded circle var rightfootgeo = new THREE.CubeGeometry(2, 2, 2); for(var i = 0; i < ...

Can Selenium be used to retrieve the CSS selector?

My current task involves scraping the following webpage: here. I am focused on extracting all images from this website, but unfortunately, they do not have any size (width, height) attributes included. Consequently, when extracted, the images appear too la ...

Error: The 'then' method cannot be invoked on an undefined object in the Parse.File.save function

I am currently utilizing the Javascript API for parse.com within an Angular JS application. My goal is to successfully save or update the user's profile picture. Below is the code snippet that I have been working with: Some HTML . . . <input type ...

What mistakes did I make in my Ajax code?

My aim is to dynamically add items to my listbox when a button is clicked, and then retrieve the value of the added item in the listbox using ajax. Below is the code I have tried: $('#right').click(function () { alert("Start process"); ...

How to make a list with a scroll bar in an HTML table cell

Having trouble creating a scrollable list in a dynamically appended HTML table cell using JavaScript? You're not alone. Even after assigning the list to the cell parent, it seems that the list is not behaving as expected - it's not scrollable and ...

Uploading files using Ajax in the Laravel framework

I am attempting to utilize ajax to upload a file in Laravel. $("#stepbutton2").click(function(){ var uploadFile = document.getElementById("largeImage"); if( ""==uploadFile.value){ } else{ v ...

Array filtering using one array condition and additional boolean conditions

Sorting through the carArray based on user-specified conditions. If a user selects the red checkbox, only cars with red paint will be displayed. If a user selects the green checkbox, only cars with green paint will be displayed. If both the red and green ...

Attempting to collapse the offcanvas menu in React Bootstrap by clicking on a link

Currently, I am utilizing a mix of React Bootstrap and React to develop a single-page application. In an attempt to make the Offcanvas menu close when clicking a link, I have experimented with various approaches. One method involved creating an inline scri ...