[英]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 document.getElementsByClassName( “伟大的-banner.live横幅”)。style.backgroundimage
window.getComputedStyle(document.getElementsByClassName(".great-banner.live-banner"),false); window.getComputedStyle(document.getElementsByClassName( “大-banner.live横幅。”),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 window.getComputedStyle(document.getElementsByClassName('。great-banner.live-banner')[0],null).getPropertyValue('background-image')。split(/'|“ /)[1];和i'我得到以下错误
Error: Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'. 错误:未捕获TypeError:无法在“ Window”上执行“ getComputedStyle”:参数1的类型不是“ 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. 首先
document.getElementsByClassName
将返回元素的集合,因此没有style
属性。 - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName -https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementsByClassName
Secondly, the argument you pass to the function should be a class name, not a css selector. 其次,传递给函数的参数应该是类名,而不是css选择器。 Maybe you are looking for
querySelectorAll
- https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll 也许您正在寻找
querySelectorAll
- https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelectorAll
Try document.querySelectorAll(".great-banner.live-banner")[0].style.backgroundImage
instead 请尝试
document.querySelectorAll(".great-banner.live-banner")[0].style.backgroundImage
代替
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 在硒中使用时,按上一行在脚本中添加“ return”,否则将提供空值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.