javascript - 如何使用 Cheerio 获取 style= background-img URL
问题描述
我正在尝试获取背景图片的 URL。背景图像位于 a href 标记中。
一个href标签,style="background-img:url("")"
我正在使用cheerio(类似于Jquery 的node.js 模块)。当我试图得到它时,它给了我错误,
TypeError:无法读取未定义的属性“替换”
我的代码是:
$("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="{"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 没有这些方法,你需要使用 attr():
// untested, I have no idea what your element looks like
$(a).attr('style').match(/url\("(.*?)"/)[1]
推荐阅读
- pyqt5 - 将表格小部件导出为 excel 文件时出现问题
- ambari - 运行 ambari 服务的单个主机(当前机器)的 Ambari 服务器主机注册失败
- kubernetes - 如何确定 Kubernetes 集群的最佳实现
- android - logcat中的数百个随机错误
- php - 选择PHP表单获取所有值
- python-3.x - Bokeh ColumnDataSource 行未呈现
- sql - 存储选择结果并使用循环在 PL/SQL 块中进行测试
- database - 是否可以使用 eloquent 在 laravel 中定义 is-a 关系?
- docker - docker:来自守护进程的错误响应:驱动程序在端点上编程外部连接失败
- python-3.x - 在同一个笔记本上运行两个模型