获取内联CSS背景图像

时间:2015-01-22 20:48:18

标签: css html5 xpath background-image

我有一个包含嵌入式CSS的节点。我试图使用XPath获取background-image: url()

<div class="ytp-thumbnail html5-stop-propagation" style="background-image: url(https://i.ytimg.com/vi_webp/lm5CLm4ciQg/hqdefault.webp);">

到目前为止,我的尝试和不完整路径是//div[@class="ytp-thumbnail"]/@style/

1 个答案:

答案 0 :(得分:0)

您的XPath无法正常工作,因为该课程与ytp-thumbnail匹配但ytp-thumbnail html5-stop-propagation不匹配。你可以使用

检查它是否匹配
//div[@class = "ytp-thumbnail html5-stop-propagation"]/@style 

或只是检查类属性contains() ytp-thumbnail

//div[contains(@class,"ytp-thumbnail")]/@style

返回

style="background-image: url(https://i.ytimg.com/vi_webp/lm5CLm4ciQg/hqdefault.webp);"

如果您只想要该值,可以使用string()

string(//div[contains(@class,"ytp-thumbnail")]/@style)

返回

background-image: url(https://i.ytimg.com/vi_webp/lm5CLm4ciQg/hqdefault.webp);

如果您只想要网址的价值,可以使用substring-before()substring-after()

substring-before(substring-after(string(//div[contains(@class,"ytp-thumbnail")]/@style),'url('),')')

返回

https://i.ytimg.com/vi_webp/lm5CLm4ciQg/hqdefault.webp

请注意,此外,由于最后的/ - /@style而不是/@style/,您的XPath不起作用 - 因为您的XPath已经选择了样式属性使用/@style