Using JavaScript to Access Embedded Image Data in Selenium Webdriver

Can anyone help me extract the src from the HTML code provided below? I'm wondering if it's possible to retrieve embedded image data using JavaScript. Also, is there a way to display hidden elements? Currently, I am utilizing Selenium WebDriver with Java.

<div id="sc859" class="atv4 alc sc-view c-image sc-hidden" style="left: 0px; right: 0px; top: 0px; bottom: 0px">
    <img style="height: 100%; width: 100%;" src="data:image/gif;base64,R0lGODlhAQABAJAAAP///wAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==" class="alc-img"/>
</div>

This is how I've attempted to handle it:

JavascriptExecutor jse = (JavascriptExecutor)driver; 
WebElement element = driver.findElement(By.cssSelector("#sc859")); 
String imgeJs = (String) jse.executeScript("document.getElementsById('sc859')[0].getAttribute('src');", element);
System.out.println(imgeJs);

Answer №1

Give this a shot:

WebElement section = driver.findElement(By.id("sc859"));
String picture =  section.findElement(By.className("alc-img")).getAttribute("src");

System.out.println(picture);

Answer №2

In my experience, I've found that using the code

document.getElementsById('sc859')[0].getAttribute('src');
never seems to work for me in the past. Instead, I tend to directly execute the script as shown below. I hope this is what you were looking for. Additionally, please note that the attribute src does not belong to the div element but rather to an img tag, so your selector was incorrect.

String src = (String) ((JavascriptExecutor)driver).executeScript("return document.querySelector(\"#sc859>img\").getAttribute(\"src\");");

System.out.println(src);

Here is the output:

data:image/gif;base64,R0lGODlhAQABAJAAAP///wAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==

Answer №3

Avoiding the need for JavaScript is possible, and you can simplify Francesco's solution by using this code snippet:

String src = driver.findElement(By.cssSelector("#sc859 > img.alc-img")).getAttribute("src");

Answer №4

Here are 3 common mistakes you might be making -

1 - getElementsById should actually be getElementById, which will only return a single element, not a collection of elements. There is no method called getElementsById as far as I know.

2 - You seem to be missing the return statement in your executeScript method.

3 - The div element whose id you have provided does not have a src attribute. The src attribute is usually associated with img elements, not div elements.

Your updated code should look something like this:

String imgeJs = jse.executeScript("return document.getElementById('sc859').childNodes[1].getAttribute('src')").toString();

Alternatively, you can achieve the same result by using the following code:

WebElement element = driver.findElement(By.cssSelector("#sc859" > img.alc-img));
String imgeJs = jse.executeScript("return arguments[0].getAttribute('src')", element).toString();

Otherwise, you can simply use the element.getAttribute("src") method from the WebElement interface as suggested in other answers.

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

The Spring Boot application refuses to launch when initiated from the VSCode terminal, yet it functions perfectly when launched via the "Boot Dashboard" plugin in Eclipse

While attempting to start my backend API Spring Boot project from the VS Code or Eclipse bash terminal, I encounter the following error: 10-15 07:38:37,212 org.springframework.context.support.AbstractApplicationContext:refresh WARN - Exception encountered ...

maintaining the longevity of an android service

I'm looking to keep an Android service running continuously, even when the phone is locked. I've experimented with Job Intent Service and Work Manager, but they don't allow for a long-running service. The purpose of this service is to make p ...

Mailchimp fails to deliver response with a Status code of 404

I attempted to use the mailchimp API to set up a mailing list for my newsletter, but I keep getting a 404 error in response. I have double-checked everything multiple times, and it still shows the 404 error. Perhaps the endpoint is incorrect, even though ...

Switch between two menu tabs on a website using HTML and Javascript

Currently, I am facing an issue where I can only toggle between two tabs that display different graphs. The page always opens with the first tab selected, and while I can switch to the second tab initially, I cannot go back to the first one afterwards. My ...

A guide to creating a reference between two tables using the hasOne method in sequelize.js

After generating 3 models using sequelize-auto, let's take a look at them: sequelize.define('users', { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: ...

Exploring the power of Lingui and yup validation within the NextJS framework

I'm using react-hook-form, yup in NextJS for form validation. I also implemented Lingui for internationalization by following this documentation. How can I set up internationalization in the yup validator that is supported by Lingui? The issue I am e ...

Loop through the JSON data to generate clickable links in the innerHTML

I've been searching through various resources for a solution to the issue I'm facing. My goal is to iterate through a JSON object and extract all the ids and corresponding dates from each top_worst section. The structure of the JSON data is as fo ...

What steps should I follow to properly configure my TypeScript Node.js project?

I have been struggling with this problem for hours and can't seem to find a solution. I am interested in creating a nodejs app using typescript. I prefer using the import statement like import express from 'express'; because it provides aut ...

Expanding and contracting div animations

My goal is to create a never-ending animation for a div element: $(document).ready(function() { function arrowmovement() { setTimeout(function() { $("#downarrowimg").animate({ 'margin-top': "-=30px" }); }, 500); ...

What is the best method for integrating static files (such as css, images, js, etc.) into our Node.js application?

Here is the structure of my project folder: XYZ_PROJECT_FOLDER ASSETS CSS IMAGES JS VENDOR CONTACT.html INDEX.html INDEX.js In the INDEX.js file, I have included code to render all the static files and routing logic: const e ...

Setting up the Java plugin for Chrome on Ubuntu

Although everything works fine in Ubuntu with my JDK, including IDE and some apps, I encountered a message in Chrome stating that Java(TM) is required to display this content I need to run an applet. How can I do so? It must be done in Chrome due to the p ...

Diverse Range of Exports Available in React Component Library

I have been working on developing a component library consisting of multiple independent components. My objective is to enable users to easily import and use these components in their projects, similar to the following: import One from 'component-lib ...

Updating Icons Using jQuery Click Function

I have a group of links with icons on them. When a link is clicked, the associated icon changes to a loading image to indicate that the link is active. The issue arises on subsequent clicks, as the loading image does not revert back to the icon and multip ...

What is the best way to incorporate animation into Bootstrap dropdowns?

Is there a way to incorporate animation into the dropdown feature? I'm assuming it can be achieved by adjusting popperConfig, but how exactly? Currently, the dropdown-menu has an automatically generated inline style, for example: position: absolute; ...

"Using .prependTo() and .insertAfter() functions without the need for jQuery

Can you explain how to achieve the following functionality without using jQuery? document.querySelector('.html-content.detail-content').insertAdjacentHTML('beforebegin', '<div id="rich-content"></div>'); I want t ...

JavaScript not executing script when key is pressed

Currently, I am learning JavaScript and facing an issue. The spaceship in my game is not moving despite no error being present. Pressing the key w on my keyboard does not trigger any action. I suspect that the problem lies within the line "document.on ...

An error occurred while trying to call the virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference

I'm currently working on developing an app that allows users to upload images and videos to a server. Initially, this feature worked flawlessly within an activity, but now I am attempting to implement it in a fragment. Despite coding efficiently and e ...

What are the best techniques for creating animations in AngularJS?

I've been trying to figure out how to animate in AngularJS by searching online, but I haven't found a perfect solution yet. html <span class="sb-arrow down" ng-click="hideSampleList($event)"></span> ...

What steps can be taken in Next.js to display a 404 page when data is not retrieved from the Wordpress admin?

I am working with JSON data that looks like this: [ { "taxonomy_slug": "product_cat", "taxonomy_name": "Categories", "frontend_slug": "product-category" }, { ...

Implementing Vuejs Array Push in Separate Components

I am attempting to extract data from an object and store it in an array using Vue. My goal is to have each value stored in a separate array every time I click on an item. Each click should push the todo into a different array. How can I achieve this separa ...