HTML 页面中所有嵌入对象的 URL

URLs of all embedded objects in a HTML page

本文关键字:对象 URL HTML      更新时间:2023-09-26

您将如何获取嵌入到网页中的所有对象的URL(或仅主机名(?您将使用哪种标签-属性组合?(还是别的什么?

例如,Stackoverflow 页面的开头如下所示

<!DOCTYPE html>
<html>
<head>
<title>Stack Overflow</title>
    <link rel="shortcut icon" href="//cdn.sstatic.net/stackoverflow/img/favicon.ico?v=4f32ecc8f43d">
    <link rel="apple-touch-icon image_src" href="//cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a">
[...]   
    <meta property="og:image" itemprop="image primaryImageOfPage" content="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&a" />

在这里,URL//cdn.sstatic.net/stackoverflow/img/favicon.ico?v=4f32ecc8f43d 和//cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a 位于 href 属性中,而 http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&a 位于content属性中。此外,图像和脚本具有src属性。

images HTMLCollection 将是一个起点,但 DOM 规范建议

不使用此属性查找文档中的图像,而是getElementsByTagName

标签.要考虑的属性组合:a.hrefimg.srclink.hrefscript.srcmeta.content。还有哪个?

这是一种给定正确标签组合的方法。这是锚标记的示例:

var urls = [];
var allA = document.getElementsByTagName("A");
for ( var i = 0; i < allA.length; i++ ) {
    if ( typeof allA[i].href === "string" && allA[i].href !== "" ) {
      urls.push(allA[i].href);
    }
}

可以对所有标记-属性组合重复此操作。

我错过了哪些具有哪些属性的标签?

标签<a><meta>太多了:<a>元素没有嵌入,<meta>发现了一些URL,但也没有嵌入。因此,尝试看起来像

function getAttributeFromTags(tag, attribute) {
  var out = [];
  var allA = document.getElementsByTagName(tag);
  for (var i = 0; i < allA.length; i++) {
    if (typeof allA[i][attribute] === 'string' && allA[i][attribute] !== '') {
      out.push(allA[i][attribute]);
    }
  }
  return out;
}
var urls = [];
Array.prototype.push.apply(urls, getAttributeFromTags('AUDIO', 'src'));
Array.prototype.push.apply(urls, getAttributeFromTags('EMBED', 'src'));
Array.prototype.push.apply(urls, getAttributeFromTags('IMG', 'src'));
Array.prototype.push.apply(urls, getAttributeFromTags('LINK', 'href'));
Array.prototype.push.apply(urls, getAttributeFromTags('OBJECT', 'data'));
Array.prototype.push.apply(urls, getAttributeFromTags('SCRIPT', 'src'));
Array.prototype.push.apply(urls, getAttributeFromTags('SOURCE', 'src'));
Array.prototype.push.apply(urls, getAttributeFromTags('VIDEO', 'src'));

警告

  • 使用link.href包含太多的URL(例如,请查看view-source:https://www.youtube.com/watch?v=kPUglMKGXRM(SO不允许查看源链接...((。

实现

HTMLCollection不提供forEach(除了使用奇怪的语法(,并且解决方法没有得到广泛支持。