【问题标题】:Retrieving all of url from document text(content)从文档文本(内容)中检索所有 url
【发布时间】:2016-01-12 03:34:45
【问题描述】:

我正在开发工具来检查所有类型资源的状态,例如 js、css、img 等以及给定网站的其他 url。

例如给定网址:www.abc.com 然后我需要检查 www.abc.com 的所有类型资源和 url 的状态

为此,我正在使用 jquery ajax...因此,我将获得该 url (abc.com) 的 html 内容

但问题是如何从该 html 内容中找到所有 url?我尝试了很多方法,但不知道如何获得。

请为此提供一些好的解决方案。

提前致谢。

【问题讨论】:

    标签: javascript jquery seo


    【解决方案1】:

    尝试使用.each()迭代imglinkscript元素;检索srchref 属性值

    $("img, link, script").each(function() {
      // do stuff with `this.src` or `this.href`
      console.log(this.src || this.href)
    })
    

    【讨论】:

    • 这是相对简单的解决方案!在表单、iframe 等其他标签中可能有其他可能性,因此我们无法静态查询标签。
    • “在表单、iframe 等其他标签中可能有其他可能性,因此我们无法静态查询标签” 尝试用$("[src],[href],[method],[action]") 选择器替换$("img, link, script")选择器,添加检查methodaction属性,如果需要,在.each()回调中
    • 这是更好的主意。感谢您的帮助。
    【解决方案2】:
      $('a, img, link, script').each(function () {
            console.info($(this).attr('href'));
            console.info($(this).attr('src'));
        });
    

    【讨论】:

      【解决方案3】:

      如果您想使用纯 JavaScript 获取所有“URL”。

      HTML:

      <a href="www.google.com">1</a>
      <br>
      <a href="www.facebook.com">2</a>
      <br>
      <a href="www.yahoo.com">3</a>
      <br>
      <a href="www.bing.com">4</a>
      <br>
      <a href="www.youtube.com">5</a>
      <br>
      <a href="www.iRanOutOfNames.com">6</a>
      <br>
      

      JavaScript:

      function getURLs(url) {
        //create an empty array
        var array = [];
        // get all <a> tags
        //note: you can do that with <img/> tags or any
        //I only used the <a> tag for the sake of time
        url = document.getElementsByTagName("a");
        //loop through all of the elements
        for (var i = 0; i < url.length; i++) {
          //when done, add all the elements inside the empty array
          array.push(url[i].href);
        }
        //alert them
        alert(array);
      }
      //call the function
      getURLs();
      

      演示:jsfiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-14
        • 2021-07-11
        • 2019-12-15
        • 1970-01-01
        • 2012-06-24
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多