Подтвердить что ты не робот

Как анализировать RSS-канал с помощью JavaScript?

Мне нужно разобрать RSS-канал (XML-версия 2.0) и отобразить проанализированные детали на странице HTML.

4b9b3361

Ответ 1

Разбор фида

С jQuery jFeed

(Не рекомендую это, см. другие параметры.)

jQuery.getFeed({
   url     : FEED_URL,
   success : function (feed) {
      console.log(feed.title);
      // do more stuff here
   }
});

С jQuery Встроенная поддержка XML

$.get(FEED_URL, function (data) {
    $(data).find("entry").each(function () { // or "item" or whatever suits your feed
        var el = $(this);

        console.log("------------------------");
        console.log("title      : " + el.find("title").text());
        console.log("author     : " + el.find("author").text());
        console.log("description: " + el.find("description").text());
    });
});

С jQuery и API Google AJAX Feed

$.ajax({
  url      : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
  dataType : 'json',
  success  : function (data) {
    if (data.responseData.feed && data.responseData.feed.entries) {
      $.each(data.responseData.feed.entries, function (i, e) {
        console.log("------------------------");
        console.log("title      : " + e.title);
        console.log("author     : " + e.author);
        console.log("description: " + e.description);
      });
    }
  }
});

Но это означает, что вы надеетесь, что они будут в сети и доступны.


Содержание здания

После того, как вы успешно извлекли нужную информацию из фида, вы можете создать DocumentFragmentdocument.createDocumentFragment(), содержащий элементы (созданные с помощью document.createElement()), вы захотите для отображения ваших данных.


Ввод содержимого

Выберите элемент контейнера, который вы хотите на странице, и добавьте к нему фрагменты документа, и просто используйте innerHTML, чтобы полностью заменить его содержимое.

Что-то вроде:

$('#rss-viewer').append(aDocumentFragmentEntry);

или

$('#rss-viewer')[0].innerHTML = aDocumentFragmentOfAllEntries.innerHTML;

Данные тестирования

Используя этот фид вопроса, который на момент написания дает:

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0">
    <title type="text">How to parse a RSS feed using javascript? - Stack Overflow</title>
    <link rel="self" href="/questions/56395/how-to-parse-an-rss-feed-using-javascript" type="application/atom+xml" />
        <link rel="hub" href="http://pubsubhubbub.appspot.com/" />        
    <link rel="alternate" href="https://stackoverflow.com/q/10943544" type="text/html" />
    <subtitle>most recent 30 from stackoverflow.com</subtitle>
    <updated>2012-06-08T06:36:47Z</updated>
    <id>/questions/56395/how-to-parse-an-rss-feed-using-javascript</id>
    <creativeCommons:license>http://www.creativecommons.org/licenses/by-sa/3.0/rdf</creativeCommons:license> 
    <entry>
        <id>https://stackoverflow.com/q/10943544</id>
        <re:rank scheme="http://stackoverflow.com">2</re:rank>
        <title type="text">How to parse a RSS feed using javascript?</title>
        <category scheme="/questions/56395/how-to-parse-an-rss-feed-using-javascripttags" term="javascript"/><category scheme="/questions/56395/how-to-parse-an-rss-feed-using-javascripttags" term="html5"/><category scheme="/questions/56395/how-to-parse-an-rss-feed-using-javascripttags" term="jquery-mobile"/>
        <author>
            <name>Thiru</name>
            <uri>https://stackoverflow.com/users/1126255</uri>
        </author>
        <link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript" />
        <published>2012-06-08T05:34:16Z</published>
        <updated>2012-06-08T06:35:22Z</updated>
        <summary type="html">
            &lt;p&gt;I need to parse the RSS-Feed(XML version2.0) using XML and I want to display the parsed detail in HTML page, I tried in many ways. But its not working. My system is running under proxy, since I am new to this field, I don&#39;t know whether it is possible or not. If any one knows please help me on this. Thanks in advance.&lt;/p&gt;

        </summary>
    </entry>
    <entry>
        <id>https://stackoverflow.com/questions/10943544/-/10943610#10943610</id>
        <re:rank scheme="http://stackoverflow.com">1</re:rank>
        <title type="text">Answer by haylem for How to parse a RSS feed using javascript?</title>
        <author>
            <name>haylem</name>
            <uri>https://stackoverflow.com/users/453590</uri>
        </author>    
        <link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript/10943610#10943610" />
        <published>2012-06-08T05:43:24Z</published>   
        <updated>2012-06-08T06:35:22Z</updated>
        <summary type="html">&lt;h1&gt;Parsing the Feed&lt;/h1&gt;

&lt;h3&gt;With jQuery&#39;s jFeed&lt;/h3&gt;

&lt;p&gt;Try this, with the &lt;a href=&quot;http://plugins.jquery.com/project/jFeed&quot; rel=&quot;nofollow&quot;&gt;jFeed&lt;/a&gt; &lt;a href=&quot;http://www.jquery.com/&quot; rel=&quot;nofollow&quot;&gt;jQuery&lt;/a&gt; plug-in&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.getFeed({
   url     : FEED_URL,
   success : function (feed) {
      console.log(feed.title);
      // do more stuff here
   }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;With jQuery&#39;s Built-in XML Support&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;$.get(FEED_URL, function (data) {
    $(data).find(&quot;entry&quot;).each(function () { // or &quot;item&quot; or whatever suits your feed
        var el = $(this);

        console.log(&quot;------------------------&quot;);
        console.log(&quot;title      : &quot; + el.find(&quot;title&quot;).text());
        console.log(&quot;author     : &quot; + el.find(&quot;author&quot;).text());
        console.log(&quot;description: &quot; + el.find(&quot;description&quot;).text());
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;With jQuery and the Google AJAX APIs&lt;/h3&gt;

&lt;p&gt;Otherwise, &lt;a href=&quot;https://developers.google.com/feed/&quot; rel=&quot;nofollow&quot;&gt;Google&#39;s AJAX Feed API&lt;/a&gt; allows you to get the feed as a JSON object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$.ajax({
  url      : document.location.protocol + &#39;//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;amp;num=10&amp;amp;callback=?&amp;amp;q=&#39; + encodeURIComponent(FEED_URL),
  dataType : &#39;json&#39;,
  success  : function (data) {
    if (data.responseData.feed &amp;amp;&amp;amp; data.responseData.feed.entries) {
      $.each(data.responseData.feed.entries, function (i, e) {
        console.log(&quot;------------------------&quot;);
        console.log(&quot;title      : &quot; + e.title);
        console.log(&quot;author     : &quot; + e.author);
        console.log(&quot;description: &quot; + e.description);
      });
    }
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But that means you&#39;re relient on them being online and reachable.&lt;/p&gt;

&lt;hr&gt;

&lt;h1&gt;Building Content&lt;/h1&gt;

&lt;p&gt;Once you&#39;ve successfully extracted the information you need from the feed, you need to create document fragments containing the elements you&#39;ll want to inject to display your data.&lt;/p&gt;

&lt;hr&gt;

&lt;h1&gt;Injecting the content&lt;/h1&gt;

&lt;p&gt;Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.&lt;/p&gt;
</summary>
    </entry></feed>

Казни

Использование встроенной поддержки XML jQuery

Вызов:

$.get('/questions/56395/how-to-parse-an-rss-feed-using-javascript', function (data) {
    $(data).find("entry").each(function () { // or "item" or whatever suits your feed
        var el = $(this);

        console.log("------------------------");
        console.log("title      : " + el.find("title").text());
        console.log("author     : " + el.find("author").text());
        console.log("description: " + el.find("description").text());
    });
});

Распечатывает:

------------------------
title      : How to parse a RSS feed using javascript?
author     : 
            Thiru
            https://stackoverflow.com/users/1126255

description: 
------------------------
title      : Answer by haylem for How to parse a RSS feed using javascript?
author     : 
            haylem
            https://stackoverflow.com/users/453590

description: 

Использование jQuery и API AJAX Google

Вызов:

$.ajax({
  url      : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('/questions/56395/how-to-parse-an-rss-feed-using-javascript'),
  dataType : 'json',
  success  : function (data) {
    if (data.responseData.feed && data.responseData.feed.entries) {
      $.each(data.responseData.feed.entries, function (i, e) {
        console.log("------------------------");
        console.log("title      : " + e.title);
        console.log("author     : " + e.author);
        console.log("description: " + e.description);
      });
    }
  }
});

Распечатывает:

------------------------
title      : How to parse a RSS feed using javascript?
author     : Thiru
description: undefined
------------------------
title      : Answer by haylem for How to parse a RSS feed using javascript?
author     : haylem
description: undefined

Ответ 2

Еще один параметр устаревший (спасибо @daylight) и самый легкий для меня (это то, что я использую для SpokenToday.info):

API Google Feed без использования JQuery и всего лишь с двумя шагами:

  • Импортировать библиотеку:

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">google.load("feeds", "1");</script>
    
  • Найти/загрузить каналы (документация):

    var feed = new google.feeds.Feed('http://www.google.com/trends/hottrends/atom/feed?pn=p1');
    feed.load(function (data) {
        // Parse data depending on the specified response format, default is JSON.
        console.dir(data);
    });
    
  • Чтобы проанализировать данные, отметьте документацию о формате ответа.

Ответ 3

Если вы ищете простую и бесплатную альтернативу Google Feed API для своего виджета rss, то rss2json.com может быть подходящим решением для этого.

Вы можете попытаться увидеть, как это работает на примере кода, из документации API ниже:

google.load("feeds", "1");

    function initialize() {
      var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");
      feed.load(function(result) {
        if (!result.error) {
          var container = document.getElementById("feed");
          for (var i = 0; i < result.feed.entries.length; i++) {
            var entry = result.feed.entries[i];
            var div = document.createElement("div");
            div.appendChild(document.createTextNode(entry.title));
            container.appendChild(div);
          }
        }
      });
    }
    google.setOnLoadCallback(initialize);
<html>
  <head>    
     <script src="https://rss2json.com/gfapi.js"></script>
  </head>
  <body>
    <p><b>Result from the API:</b></p>
    <div id="feed"></div>
  </body>
</html>

Ответ 4

Если вы хотите использовать простой API JavaScript, есть хороший пример на https://github.com/hongkiat/js-rss-reader/

Полное описание на https://www.hongkiat.com/blog/rss-reader-in-javascript/

Он использует метод fetch в качестве глобального метода, который асинхронно выбирает ресурс. Ниже приведен фрагмент кода:

fetch(websiteUrl).then((res) => {
  res.text().then((htmlTxt) => {
    var domParser = new DOMParser()
    let doc = domParser.parseFromString(htmlTxt, 'text/html')
    var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
  })
}).catch(() => console.error('Error in fetching the website'))

Ответ 5

Для всех, кто читает это (начиная с 2019 года), к сожалению, большинство реализаций чтения JS RSS сейчас не работают. Во-первых, Google API отключился, так что это больше не вариант, и из-за политики безопасности CORS теперь вы обычно не можете запрашивать RSS-каналы для междоменных доменов.

Используя пример https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015), я получаю следующее:

Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Это правильно и является мерой безопасности конечного веб-сайта, но теперь это означает, что приведенные выше ответы вряд ли сработают.

Мой обходной путь, вероятно, будет заключаться в том, чтобы проанализировать RSS-канал через PHP и позволить javascript получить доступ к моему PHP, а не пытаться получить доступ к самому конечному каналу.

Ответ 6

Вы можете использовать jquery-rss или Vanilla RSS, который поставляется с красивыми шаблонами и очень прост в использовании:

// Example for jquery.rss
$("#your-div").rss("https://stackoverflow.com/feeds/question/10943544", {
    limit: 3,
    layoutTemplate: '<ul class="inline">{entries}</ul>',
    entryTemplate: '<li><a href="{url}">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'
})

// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
    document.querySelector("#your-div"),
    "https://stackoverflow.com/feeds/question/10943544",
    { 
      // options go here
    }
);
rss.render().then(() => {
  console.log('Everything is loaded and rendered');
});

Смотрите http://jsfiddle.net/sdepold/ozq2dn9e/1/ рабочий пример.