【问题标题】:How To Get style= background-img URL Using Cheerio如何使用 Cheerio 获取 style= background-image URL
【发布时间】:2021-01-02 10:37:45
【问题描述】:

我正在尝试获取背景图片的 URL。背景图片在 a href 标记中。

一个href标签,style="background-img:url("")"

我正在使用cheerio(类似于Jquery 的node.js 模块)。当我试图得到 它给了我错误,

TypeError: Cannot Read Property "replace" for undefined

我的代码是:

$("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();

这是需要背景图片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="{&quot;baseurl&quot;:&quot;https:\/\/arynews.tv\/wp-content\/uploads\/2020\/09\/&quot;,&quot;sizes&quot;:{&quot;210&quot;:&quot;shehbaz-1-1-210x136.jpg&quot;,&quot;279&quot;:&quot;shehbaz-1-1-279x220.jpg&quot;,&quot;357&quot;:&quot;shehbaz-1-1-357x210.jpg&quot;,&quot;750&quot;:&quot;shehbaz-1-1.jpg&quot;}}" class="img-holder    b-loaded" href="https://arynews.tv/en/nab-money-laundering-reference-shehbaz-sharif/" style="background-image: url(&quot;https://arynews.tv/wp-content/uploads/2020/09/shehbaz-1-1-279x220.jpg&quot;);"></a>
</div>

【问题讨论】:

  • jQuery 没有问题所以你确定选择器是对的吗?你能告诉我们元素的 CSS 吗?
  • cannot read property for undefined - 只需添加一个子句,例如 let imgURL = $(this).css("background-image") || "";
  • 我正在使用 Cheerio,它类似于 Jquery。但我得到了未定义。

标签: javascript html jquery node.js cheerio


【解决方案1】:

使用不带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

你会收到类似的字符串

"url("http://localhost:1337/uploads/offline_reset_45146034ad.jpg") center center no-repeat"

下一步是通过正则表达式从该字符串中获取 URL。

还有你的例子:

imgURL.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')

伟大的奉献

"http://localhost:1337/uploads/offline_reset_45146034ad.jpg"

【讨论】:

  • 它返回我 imgURL='' 我该怎么办?
  • 显示 document.querySelector(selector).innerHTML 并将其粘贴到您的问题中
  • 我在问题上方添加了元素。检查一下,我想获取img URL。这是样式背景img url
【解决方案2】:

cheerio 没有这些方法,你需要使用 attr():

// untested, I have no idea what your element looks like
$(a).attr('style').match(/url\("(.*?)"/)[1]

【讨论】:

  • 非常感谢!我试过了,但没有用。虽然,我已经添加了元素,请检查上面。我需要有风格的背景图片 URL。
  • 成功了,谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
  • 2017-03-04
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多