![](/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.