[英]How To Get style= background-img URL Using Cheerio
I'm trying to get the URL of the background image.我正在尝试获取背景图像的 URL。 The background image is in the a href tag.背景图片在 a href 标签中。
a href tag, style="background-img:url("")"
一个 href 标签, style="background-img:url("")"
I'm using cheerio (node.js modules similar to Jquery).我正在使用cheerio(类似于Jquery 的node.js 模块)。 While I try to get It gives me error of,虽然我试图得到它给我的错误,
TypeError: Cannot Read Property "replace" for undefined类型错误:无法读取未定义的属性“替换”
My Code Is:我的代码是:
$("div.listing.listing-blog.listing-blog-1.clearfix.columns-1.columns-1 > article > .item-inner .featured.clearfix a").map(function () {
let imgURL = $(this).css("background-image");
imgURL = imgURL.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');
return { imgURL };
}).get();
This Is The Element, From which the URL of background Image is needed:这是元素,从中需要背景图像的 URL:
<article class="post-431236 type-post format-standard has-post-thumbnail listing-item listing-item-blog listing-item-blog-1 main-term-51 bsw-5 ">
<div class="item-inner clearfix">
<h2 class="title"> <a href="https://arynews.tv/en/nab-money-laundering-reference-shehbaz-sharif/" class="post-url post-title">
POST TITLE </a>
</h2>
<div class="featured clearfix">
<a alt="nab, shehbaz sharif, pml-n, benami assets" title="NAB prepares money-laundering reference against Shehbaz Sharif: sources" data-bs-srcset="{"baseurl":"https:\/\/arynews.tv\/wp-content\/uploads\/2020\/09\/","sizes":{"210":"shehbaz-1-1-210x136.jpg","279":"shehbaz-1-1-279x220.jpg","357":"shehbaz-1-1-357x210.jpg","750":"shehbaz-1-1.jpg"}}" class="img-holder b-loaded" href="https://arynews.tv/en/nab-money-laundering-reference-shehbaz-sharif/" style="background-image: url("https://arynews.tv/wp-content/uploads/2020/09/shehbaz-1-1-279x220.jpg");"></a>
</div>
cheerio doesn't have those methods, you need to use attr(): cheerio 没有这些方法,你需要使用 attr():
// untested, I have no idea what your element looks like
$(a).attr('style').match(/url\("(.*?)"/)[1]
Using pure js
without jQuery
you can type:使用没有jQuery
纯js
,您可以输入:
const selector = `div.listing.listing-blog.listing-blog-1.clearfix.columns-1.columns-1 > article > .item-inner .featured.clearfix a`;
const imgURL = document.querySelector(selector).style.background
You will receive string like你会收到像这样的字符串
"url("http://localhost:1337/uploads/offline_reset_45146034ad.jpg") center center no-repeat"
Next step is get URL from this string by regex.下一步是通过正则表达式从此字符串中获取 URL。
And your example:还有你的例子:
imgURL.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
works great giving伟大的给予
"http://localhost:1337/uploads/offline_reset_45146034ad.jpg"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.