简体   繁体   中英

How to get the background url of the image using the javascript or selenium

I'm trying to get the background url of the image. below is the code from the webpage

 <style type="text/css"> .great-banner.live-banner { background-image: url("urloftheimage"); } </style> <div class="great-banner live-banner"> </div> 

I tried using

document.getElementsByClassName(".great-banner.live-banner").style.backgroundimage

window.getComputedStyle(document.getElementsByClassName(".great-banner.live-banner"),false); but both of these didn't work form me

I also tried

window.getComputedStyle(document.getElementsByClassName('.great-banner.live-banner')[0], null).getPropertyValue('background-image').split(/'|"/)[1]; and i'm getting the below error

Error: Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

Can you please help me how to get the background image URL

First of all document.getElementsByClassName will return a collection of elements, so there is no style property. - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

Secondly, the argument you pass to the function should be a class name, not a css selector. Maybe you are looking for querySelectorAll - https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Try document.querySelectorAll(".great-banner.live-banner")[0].style.backgroundImage instead

I found the solution:

window.document.defaultView.getComputedStyle(document.getElementsByClassName('great-banner live-banner')[0], null).getPropertyValue('background-image').split(/'|\\"/)[1]; in java script. It will return the URL.

While using in selenium:

JavascriptExecutor jsExec = (JavascriptExecutor) driver; jsExec.executeScript("return window.document.defaultView.getComputedStyle(document.getElementsByClassName('great-banner live-banner')[0], null).getPropertyValue('background-image').split(/'|\\"/)[1];"));

Add 'return' in the script as per the above line while using in selenium otherwise, it will provide null value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM