Searching for elements in Selenium using JavaScript's equivalent of findElement(by.className)

I need to locate an id tag within a class tag on an html page.

driver.find_element(By.XPATH, "//div[@class='Content warning']/p").get_attribute("id")

https://i.stack.imgur.com/NlU8t.png

I successfully accomplished this with selenium using the following instruction:

driver.find_element(By.XPATH, "//div[@class='Content warning']/p").get_attribute("id"))
 

Although it works well, it is a bit slow. I am interested in trying a javascript code injected directly into the page using a code injector.

Therefore, I am seeking the equivalent of the selenium instruction in javascript.

Answer №1

To achieve this in JavaScript:

driver.execute_script('''
  return document.querySelector('div[class="Content warning"] > p').id
''')

Answer №2

Although @pguardiario's suggestion is valid, you also have the option of accomplishing this in Python by running the JS code (and leveraging Selenium's get_attribute method).

content_warning = driver.execute_script('''
  return document.querySelector('div[class="Content warning"] > p')
''')
content_warning.get_attribute('id')

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

Accordion with searchable tabular layout

Can you search for a product within an accordion? I have 34 categories in my accordion, each with a table containing at least 10 rows. Each row has a column with an icon that stores the data of that row. Please note that I am not using jQuery tables. If ...

Implementing custom CSS styles for HighCharts API pie chart drilldown labels

I successfully created a pie chart using highcharts and configured the chart with the following options: chart: { type: 'pie', }, In order to change the width of the text on the chart, I added the following options which force e ...

What is causing ES6 Class properties to be concealed by Higher Order Functions?

UPDATE: Added new screenshots to provide clarity at the end. My current challenge involves utilizing high order functions to combine subclasses/mixins. I've noticed that I can only access properties from the first class I extend, and only properties ...

Ways to fix the loading error in AngularJS version 1.3.5?

My HTML page includes AngularJS components. Below is the code snippet: <!DOCTYPE html> <html ng-app="MyApp"> <head> <base href="/"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> &l ...

Having trouble with your custom AngularJS directive not functioning correctly?

I am facing an issue with my custom directive implementation. I have a custom directive that contains a table which references a controller. The ProjectController part works fine when it is not included in the code, but as soon as I put everything into the ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

Initiate the function once the condition is satisfied (contains the class "in-view")

Here is the code for an animation: var setInter = null; function startAnimation() { var frames = document.getElementById("animation").children; var frameCount = frames.length; var i = 0; setInter = setInterval(function () { fr ...

Adding new data to a Chart.js line graph in vue on form submission - A step-by-step guide

I'm struggling with dynamically updating my line chart with new data. I want the chart to refresh every time a user submits a form with new data. Currently, I can add new data to the datasets array in the data function of App.vue, but the chart doesn& ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...

Error 404: Postgres and NodeJs API not found (Possible duplicate)

I am new to developing with Node.js and currently working on creating APIs using node, express, and a Postgres database. const {Pool} = require('pg'); //const connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/tu ...

A step-by-step guide on integrating Google Tag Manager with a NextJS website

After consulting this answer and this article, I have implemented a <Script> tag to incorporate Google Tag Manager into my NextJS website: components/layout.tsx: import React from "react"; import Head from "next/head"; import ...

Clickable div containing a hyperlink

I need assistance with a clickable div that contains a link. Here is the setup: HTML: <div onClick="goToCat(2);" class="author-topics-block "> <a href="http://mywebsite/page/?cat=2">The woman in steel</a> </div> CSS: .author ...

Store the Ajax response in localStorage and convert it into an object for easy retrieval and manipulation

I'm currently working on an Ajax request that retrieves JSON data from the server and then stores it in localStorage for use in my application. However, I feel like my current code may not be the most efficient way to accomplish this task, as I have t ...

Is it possible to configure PhantomJS WebDriver with .pac autoproxy settings?

Can the PhantomJS WebDriver be used with Selenium and .pac autoproxy settings? The current code I am using is as follows: DesiredCapabilities capabilities = DesiredCapabilities.phantomjs(); capabilities.setJavascriptEnabled(true); capabilities.setCapabili ...

Only initiate the loading of the iframe within the div upon clicking a specific element

Is there a way to delay loading the content of a div until it's clicked, instead of having all data loaded at once when the page loads? I noticed that removing unnecessary divs made the page load much faster. How can I prevent all data from being loa ...

Encountering a JS error that states: "Uncaught SyntaxError: missing ) after argument list" when running the following code

I keep encountering the error message: "Uncaught SyntaxError: missing ) after argument list" when I try to call the delete function within the createHtmlview function. console.log("Delete Item is being called") } ...

Nodes in force-directed graphs are magnetically attracted to the central point

After finding a solution to the issue in this question Insert text inside Circle in D3 chart I have encountered an unexpected behavior where my nodes are not positioned correctly. I am unsure about which property is controlling the x and y coordinates of ...

Utilizing a jQuery variable within an .html() method

Can a Jquery if statement be used to display different content inside a div based on a variable? For example, if the variable is set to "cats", the displayed content might say "I like cats", and if it changes to "dogs", it would read "I like dogs". Is this ...

What are the steps to implement character movement in a 2D game using JavaScript?

I'm having trouble getting the image with the ID "yoshi" to move around in my 2D game document.onkeydown = (e) => { if (e.keyCode == 37) yoshi.style.left = yoshi.offsetLeft - 5 + "px"; else if (e.keyCode == 38) yoshi.style.top = yoshi.offset ...

What steps should I follow to run my JavaScript application locally on Linux Mint?

Currently, I am diligently following a tutorial and ensuring that each step is completed accurately. My goal is to locally host my javascript app at localhost:3000. Unfortunately, I am facing difficulties as every attempt to run npm run dev results in an e ...