![](/img/trans.png)
[英]How to retrieve the url from background image using Selenium and Javascript
[英]How to get the background url of the image using the javascript or selenium
我正在尝试获取图像的背景网址。 以下是网页中的代码
<style type="text/css"> .great-banner.live-banner { background-image: url("urloftheimage"); } </style> <div class="great-banner live-banner"> </div>
我尝试使用
document.getElementsByClassName( “伟大的-banner.live横幅”)。style.backgroundimage
window.getComputedStyle(document.getElementsByClassName( “大-banner.live横幅。”),FALSE); 但是这两个都不对我有用
我也试过
window.getComputedStyle(document.getElementsByClassName('。great-banner.live-banner')[0],null).getPropertyValue('background-image')。split(/'|“ /)[1];和i'我得到以下错误
错误:未捕获TypeError:无法在“ Window”上执行“ getComputedStyle”:参数1的类型不是“ Element”。
能否请您帮我获取背景图片网址
首先document.getElementsByClassName
将返回元素的集合,因此没有style
属性。 -https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementsByClassName
其次,传递给函数的参数应该是类名,而不是css选择器。 也许您正在寻找querySelectorAll
- https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelectorAll
请尝试document.querySelectorAll(".great-banner.live-banner")[0].style.backgroundImage
代替
我找到了解决方案:
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.
在硒中使用时:
JavascriptExecutor jsExec = (JavascriptExecutor) driver; jsExec.executeScript("return window.document.defaultView.getComputedStyle(document.getElementsByClassName('great-banner live-banner')[0], null).getPropertyValue('background-image').split(/'|\\"/)[1];"));
在硒中使用时,按上一行在脚本中添加“ return”,否则将提供空值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.