A guide on extracting the URL from a background image utilizing Selenium and JavaScript

I've been attempting to extract the URL from a background image using Xpath or Javascript, but so far I haven't had any success. Here's what I currently have:

<div style="width: 100%; display: inline-block;">
 <div tws-article-images-preload="item" class="tws-article-images--preload ng-scope tws-article-images-- 
   image-small" ng-click="closeImage()" use-original="useOriginal" style="background-image: 
   url(&quot;https://i.pinimg.com/originals/59/54/b4/5954b408c66525ad932faa693a647e3f.jpg;);">
 </div>
</div>

I've experimented with different modifications of the following two methods to try and achieve this goal:

//*[starts-with(@style, 'background-image: url()] <--This did not work 

return document.getElementsByClassName('tws-article-images--preload ng-scope tws-article-images--image-small').src

Answer №1

Grab the background image URL from the first element with class 'classname', remove unnecessary characters, and replace any double quotes.

Answer №2

If you want to test it out

let bgImage = document.getElementsByClassName('tws-article-images--preload ng-scope tws-article-images--image-small').style.backgroundImage.slice(4, -1).replace(/["']/g, "");
return bgImage;

Answer №3

Your XPath query seems to have a mistake (missing ' and there might be an unwanted CRLF). Here's how you can correct it:

//*[starts-with(@style, 'background-image:')]/@style

You can then use regular expressions to clean up the output:

txt = 'background-image: url("https://i.pinimg.com/originals/59/54/b4/5954b408c66525ad932faa693a647e3f.jpg;);'
result = re.sub(r"^.+\"(.+?);.+", r"\1", txt)
print(result)

To extract the URL using XPath:

substring-after(substring-before(//*[starts-with(@style, 'background-image:')]/@style,';)'),'"')

Output :

https://i.pinimg.com/originals/59/54/b4/5954b408c66525ad932faa693a647e3f.jpg

Answer №4

If you want to extract the url from a background image, you have two options:

  • Method 1: Using slice():

    var img = document.getElementsByClassName('tws-article-images--preload')[0],
    style = img.currentStyle || window.getComputedStyle(img, false),
    bgImage = style.backgroundImage.slice(4, -1).replace(/"/g, "");
    //displaying the URL
    console.log('Background Image URL: ' + bgImage);
    
  • Method 2: Utilizing regex:

    var img = document.getElementsByClassName('tws-article-images--preload')[0],
    style = img.currentStyle || window.getComputedStyle(img, false),
    var url = backgroundImage.match(/url\(["']?([^"']*)["']?\)/)[1];
    //displaying the URL
    console.log('Background Image URL: ' + url);
    

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

Adding additional `select` dynamically causes the value to disappear from view

After attempting to replicate the functionality of the select field, I encountered an issue where it no longer displays any values. Specifically, if I opt for a small size, I encounter this error message in the console. https://i.stack.imgur.com/5hKX6.png ...

Is there an Angular counterpart to Vue's <slot/> feature?

Illustration: Main component: <div> Greetings <slot/>! </div> Subordinate Component: <div> Planet </div> Application component: <Main> <Subordinate/> </Main> Result: Greetings Planet! ...

Iterate over the table data and present it in the form of a Google

I'm struggling to extract data from a table and display it in a google chart. I need some guidance on how to properly loop through the information. HTML <tr> <th>Date</th> <th>Score</th> <th>Result< ...

The YUI framework is skilled at creating new lines while erasing the old ones

I am looking to create a line when the mouse is clicked, and remove the previously drawn line. View the code on jsfiddle.net at this link. While my current code successfully draws a line when the mouse is clicked, it does not remove the previous line. I n ...

Can you list out the directives that are responsible for generating child scopes in AngularJS?

I recently discovered that when using ng-if, it actually creates a child scope, leading to some confusion on my end. I'm curious about the reasons or benefits behind ng-if's scope creation. Can you also tell me which other built-in directives cre ...

Determine whether an array contains any unique characters

I am attempting to determine if a password string includes any special characters. I am trying to achieve this using the code below: const passwordArr = "A1b2c3d4e5!@#".split(""); const specialChar = "~!@#$%^&*_-+=`|(){}[]:;& ...

Having trouble getting a Jquery function to properly call a PHP file

Below is my code containing two files, a javascript file and a PHP file. I am attempting to call the PHP file from the JavaScript, but I encounter a 500 internal server error when the jQuery function is invoked. Upon inspecting the Chrome web developer t ...

Incorporate a basic CSS request

Apologies for my poor English. I have the following PHP code. Now, I am looking to incorporate some CSS into this code snippet. <?php $post_objects = get_field('awncn'); if( $post_objects ): ?> <ul> <?php foreach( $post ...

What is the best way to make a select tag read-only before the Ajax request is successful

Is there a way to make a select tag read-only before an Ajax success? I tried using this code, but it didn't work: $("#tower").prop('readonly', true); Then I tried this alternative, but I couldn't get the value from the select tag: ...

Tips for implementing text-overflow ellipsis in an HTML input box?

On my website, I have input fields where I've added the following CSS styling: .ellip { white-space: nowrap; width: 200px; overflow: hidden; -o-text-overflow: ellipsis; -ms-text-overflow: ellipsis; text-overflow: ellipsis; } H ...

What could be the reason behind the malfunctioning of my three.js lighting system?

I am struggling to identify the issue with this code snippet (http://jsfiddle.net/resistdesign/s6npL/). Despite referencing the documentation and some examples, the lights don't seem to be functioning as expected. var camera, scene, renderer, geometr ...

Python Selenium is having trouble locating an element by its XPath inside the #shadow-root (open) when using both Python and Selenium

While exploring the contents of this site: I attempted to click on the button labeled as: "Alle bestätigen" using the script provided below: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui imp ...

Eliminate any empty spaces and gaps present between div elements

Is there a way to eliminate the spaces between div containers at the bottom part of the div with a red border? The following code snippets utilize materializecss. /*############################ LOGIN STYLE ############################*/ body{ font: ...

How can I fill the space around a centrally aligned div?

I'm looking to create a centered div with additional divs or spans on each side to fill the empty space. Currently, I am using margining to center the div and you can see the implementation in this example. HTML Code: <div id='A> <d ...

When trying to manually trigger the firing of the autocomplete function to get a place using Google API

My goal is to retrieve the data from autocomplete.getPlace() when triggering this event manually. Essentially, I have a function that captures the user's location in Lat/Lng format, and afterward, I aim to access other useful data using getPlace() su ...

The click function may need an additional click to complete its execution, but ideally, it should be accomplished in just one click

I have a script that filters elements on a webpage by checking the data attribute of the clicked element against class names on the filtered items (.filter-boy). As the elements are categorized into Categories and Subcategories, I aim to hide any parent c ...

There is no data found in the reports for Ant Junit and Selenium

I have been conducting multiple tests in Eclipse using Ant and Selenium WebDriver. Although the tests are running smoothly and I can view the results in the console, the generated HTML report does not include the results. Below is a snippet from my build.x ...

Valid ways to ensure that a CSS image expands outside the boundaries of the containing div

I have inserted an image using the following CSS code: .imgtemp { float:right; top:0px; left:0px; overflow:visible; width:100%; } Although I have added the div tag to display it on the page, ...

Looking for a Regex pattern for this example: 12345678/90 MM/DD/YYYY

I am having success with the first 10 digits spaced apart, but unfortunately my date regex is not working as expected. ^(\d{6}\s{2}|\d{8})\/(\d{1}\s|\d{2})\s\/(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))&bso ...

The utilization of the <span> tag featuring a {float:right] property causes container expansion in Internet Explorer 7

Within my HTML code, I have an A tag button that contains a Span element to hold icons. This setup functions correctly in most browsers, except for IE7. When I attempt to float the Span to the right side using CSS, it causes issues specifically in IE7, cau ...