我正在使用以下方法从文档的一部分中提取图像:
var theImg = document.getElementById('imageDiv').innerHTML;
这会返回类似的东西
theImg = <img src="http://website.com/image.jpg?&image-presets&" alt="foo" style="z-index: 1" />
如果没有参数,我怎么能只抓取图像的 src。这样
theImg = <a href="http://website.com/image.jpg" rel="noreferrer noopener nofollow">http://website.com/image.jpg</a>
我愿意使用正则表达式、php 或 vanilla javascript。
最佳答案
未经测试,但我相信这应该可以完成工作。它首先检索图像 src
,然后剥离以 ?
开头的所有内容。
var imgDiv = document.getElementById('imageDiv');
var imgs = imgDiv.getElementsByTagName("img");
for (var i = 0; i<imgs.length; i++) {
var theImg = imgs[i].getAttribute('src').substr(0, theImg.indexOf('?'));
console.log(theImg);
// Do whatever you need to with theImg. Add to an array or whatever...
}
关于php - 从这个用 javascript 抓取的 html 中拉出 img src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6739077/