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

What methods can I use to ensure that a user's credentials are not shown in the URL?

My NextJS application sometimes behaves unexpectedly. Whenever I have a slow connection and the initial load time of the site is longer than usual, after trying to log in to the application, the credentials I entered are displayed in the URL. This happens ...

Passing all selected items from a list to the controller

I am currently facing an issue with my two multi-select lists. One list contains a full list of names while the second one holds the names that have been selected from the first list. The names are stored in a Vue array which populates the names into the s ...

Is there a way to prevent Express.js from triggering a file download in the browser?

I am attempting to preview a Word document file in the browser using an iframe: <iframe style="float:right;" src="/ViewerJS/#../demo/ohm2013.odp" width='400' height='300' allowfullscreen webkitallowfullscreen></iframe> (Fo ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

AngularJS OAuth authentication Pop-up: Waiting for JSON response

I am looking to initiate an oauth request in a new window for my project. Here is how I can open the new window: var authWindow = $window.open("/auth/google/signin", ""); After the callback, my server will respond with JSON data: app.get('/auth/ ...

How to target and set focus on dynamically generated input field when the ID is unknown

I am facing an issue with a jQuery/AJAX function that loads HTML form elements from the server. The form fields vary, and I want to set focus on the first available input field after the load is complete. I have tried: $(':input:enabled:visible:firs ...

Accessing the selected list item from an unordered list in Vue.js

How can I capture the selected item from a dropdown-style list and perform operations based on that selection? In my list, each item is associated with a key for unique identification, except for 'Create New Filter'. I am seeking guidance on ho ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

The functionality to move forward and backward in Modal Bootsrap seems to be malfunctioning

I am in need of assistance as I have encountered a major issue that has halted my work progress for several days. My goal is to implement a feature that allows users to navigate between different days both forwards and backwards. While the functionality it ...

``Look at that cool feature - a stationary header and footer that stay in place

I'm seeking advice on how to design a website with a fixed header and footer that remain consistent across all pages, with only the content area altering. I've come across a site as an example - , but couldn't figure out how it was done even ...

Steps to Remove the Displayed Image upon Click

I have a collection of images such as {A:[img1,img2], B:[img1]}. My goal is to remove the array values that correspond to previewed images upon clicking the delete button. Each image is equipped with its own delete button for this purpose. This snippet ...

When invoking Javascript, its behavior may vary depending on whether it is being called from a custom

Currently, I am in the process of implementing versioning capabilities to a custom entity called MFAs. However, I have encountered a peculiar issue. The problem arises from having a JavaScript web resource that is being invoked from two different locations ...

Unable to locate any NativeScript modules for tns-core-module/ui

I'm working on a {N}-Application and facing an issue with importing Images from the tns-core-modules/ui/image module. Unfortunately, it seems that the target cannot be found within the tns-core-module. This is my code snippet: import * as ImageModul ...

The response from Axios in NodeJs is displaying incorrect encoding

Having some trouble executing a REST call using Axios and receiving an unexpected response. try { const response = await axios.get("https://api.predic8.de/shop/products/"); console.log(response.data); } catch (error) { console.log(`[Error] -> ...

Issue with Ajax/Json: "An object of type triggers a circular reference error when attempting to retrieve a list."

Recently, I encountered an issue with my server-side method that is triggered through JSON/Ajax. The method itself functions flawlessly and sends back a list as expected. However, I seem to have made an error in my JavaScript code, leading to the following ...

Sending a document via Selenium becomes a breeze when multiple input fields with the same class are identified

My webpage is structured like this: <ul> <li> <div> <div> <span class="buttonUpload" custom="call.js">Button Upload</span> <input class=" ...

Tips for organizing an API response based on a specific field

I'm currently in the process of learning Reactjs and I've hit a roadblock with a specific question. I have successfully fetched data using axios from an API endpoint (such as countries with details like population, currencies, region, etc.) and n ...

Using Axios in Vuejs to prompt a file download dialog

I am currently working on figuring out how to trigger a file download dialog box after receiving an Ajax request from the Flask server using Axios. Here is my current client-side code snippet: <script> export default { ... exportCSV: function() { ...

Attempting to streamline this particular JavaScript function

I have been struggling with a function that I believe could be written more effectively. My goal is to simplify it while still maintaining its functionality. function changeLetters(text) { text = text.toLowerCase(); for (var i = 0; i < text.length; ...

"Adjusting the position of the Icon in the Material UI ItemList to make it closer

How can I bring this icon closer to the text? I'm not sure how to do it. When I enter developer mode, it shows me this. https://i.stack.imgur.com/WzhB1.png I am uncertain about what the purplish stuff indicates. My objective is to move the icon to t ...