0

I'm trying to retrieve the url from an background image with Xpath or Javascript, but with no luck for now. this is what I 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>

And have tried this two with different modification

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

return document.getElementsByClassName('tws-article-images--preload ng-scope tws-article-images--image-small').src
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Dymond
  • 2,158
  • 7
  • 45
  • 80
  • Does this answer your question? [How to get background image URL of an element using JavaScript?](https://stackoverflow.com/questions/14013131/how-to-get-background-image-url-of-an-element-using-javascript) – DolUnity Jun 18 '20 at 22:05
  • Why is this tagged with f#? (I'll remove it, it doesn't seem to apply) – Abel Jun 18 '20 at 23:13
  • Why is this tagged with "canopy" ? – Jonathan March Jun 18 '20 at 23:25

4 Answers4

1
document.getElementsByClassName('classname')[0].style.backgroundImage.slice(4, -1).replace(/"/g, "");
Felipe Zavan
  • 1,654
  • 1
  • 14
  • 33
1

You can try

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

Your XPath expression is wrong (missing ' and a possible annoying CRLF). Fix it with :

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

Then use regex to clean the result :

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

With XPath :

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

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

E.Wiest
  • 5,425
  • 2
  • 7
  • 12
1

To retrieve the url from the background image you can usethe following solution:

  • 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, "");
    //printing the url
    console.log('Image URL: ' + bgImage);
    
  • Using regex:

    var img = document.getElementsByClassName('tws-article-images--preload')[0],
    style = img.currentStyle || window.getComputedStyle(img, false),
    var url = backgroundImage.match(/url\(["']?([^"']*)["']?\)/)[1];
    //printing the url
    console.log('Image URL: ' + url);
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352