获取多个网址的网站标题/说明

时间:2018-01-01 18:56:30

标签: jquery html meta

我正在尝试抓取favicon,网站标题和外部网址列表的描述,最好是使用jquery。我已经成功地为我的网址同步googles favicon服务,任何人都可以解释如何实现这个网站标题和描述吗?这是我到目前为止获得的图标。

HTML

<li><a href="http://dribbble.com/">Dribbble</a></li>
<li><a href="http://behance.net">Behance</a></li>
<li><a href="http://www.danwebb.net">Dan Webb</a></li>

JQUERY

$("a[href^='http']").each(function() {
$(this).prepend('<img src="https://www.google.com/s2/favicons? domain=' + this.href + '">');
});

1 个答案:

答案 0 :(得分:2)

  • 你有一个额外的空间? domain=
  • 另外,使用this.getAttribute("href")或jQuery的$(this).attr("href")
  • 使用https !!!

$("a[href^='http']").each(function() {
   var href= this.getAttribute("href");
   $(this).prepend('<img src="https://www.google.com/s2/favicons?domain='+ href +'">';
});
<li><a href="https://dribbble.com/">Dribbble</a></li>
<li><a href="https://behance.net">Behance</a></li>
<li><a href="https://www.danwebb.net">Dan Webb</a></li>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

但你肯定会遇到这个错误

  

...已被CORS策略阻止:请求的资源上没有“Access-Control-Allow-Origin”标头。因此,“null”原因不允许访问

所以不能仅使用JS。

PHP救援:

由于直接使用AJAX的CORS策略问题来从不允许这样做的网站获取内容 - 您可以改为:

  1. AJAX GET 您的服务器上的PHP脚本将抓取外部网站
  2. 现在内容在您的域上,AJAX将使用该内容进行响应。
  3. 使用JS(jQuery)解析响应数据,以获取所需的元素属性值或文本。
  4.   

    grabber.php

    <?php
        echo file_get_contents($_GET["url"]);
    
      

    的index.html

    <ul>
        <li><a href="https://dribbble.com/">Dribbble</a></li>
        <li><a href="https://behance.net">Behance</a></li>
        <li><a href="https://www.danwebb.net">Dan Webb</a></li>
    </ul>
    
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script>
        function grabber (url, el) {
          $.ajax({
            url: "grabber.php?url="+ url,
            type: "GET",
            success: function(data){
              // console.log( data ); 
    
              var $head  = $(data).find("head");
              var title = $head.find("title").text();
              var desc  = $head.find("meta[name='author']").attr("content");
              console.log(title , desc);
              $(el).append(" - "+ title +" - "+ desc);
            }
          });
        }
    
        $("a[href^='http']").each(function () {
          var href= this.getAttribute("href");
          $(this).prepend('<img src="https://www.google.com/s2/favicons?domain='+ href +'">';
          grabber( href , this ); // this represent the current loop el.
        });
    <script>