从RSS/Atom订阅中提取图像

3

我想知道如何从 RSS 和 Atom 订阅中提取图像,以便在容器中显示订阅的缩略图、标题、描述和链接。到目前为止,我的代码(如下所示)仅从某些订阅类型中获取图像,我想知道如何获取脚本遇到的每个图像。

if (feed_image_type == "description") {
    item_img = $($(this).find('description').text()).find("img").attr("src");
} else if (feed_image_type == "encoded") {
    item_img = $($(this).find('encoded').text()).find("img").attr("src");
} else if (feed_image_type == "thumbnail") {
    item_img = $(this).find('thumbnail').attr('url');
} else {
    item_img = $(this).find('enclosure').attr('url');
}

例如,我无法弄清楚如何从以下rss源代码片段中获取图像链接:
<description>
  <![CDATA[
   <img src="https://i.kinja-img.com/gawker-media/image/upload/s--E93LuLOd--/c_fit,fl_progressive,q_80,w_636/hd6cujrvf1d72sbxsbnr.jpg" /><p>With a surprise showing of skill and, at one point, a miracle, the bottom-ranked team in the European <em>League </em>Championship Series will not end the summer winless.<br></p><p><a href="http://compete.kotaku.com/european-league-team-finally-wins-its-first-series-of-t-1797363638">Read more...</a></p>
  ]]>
</description>

3
你尝试过 $(this).find('img').attr('src') 吗? - styfle
2个回答

3
使用以下资源: 为了正确获取内容,将dataType设置为'xml'必要的
此代码是自包含且可用。
var xmlString = '<Customer><![CDATA[ <img src="y1" /> ]]></Customer>';
var xmlObj = $.parseXML(xmlString);
var cdataText = xmlObj.firstChild.firstChild.textContent;
var jqueryObj = $(cdataText);
var imgUrl = jqueryObj.find('img').attr('src');
console.log(imgUrl);

这有点不精确,因为您没有提供足够的信息来完全重现您的情况。我将从您的问题开始,假设这是您代码的唯一部分:
if (feed_image_type == "description") {
    item_img = $($(this).find('description').text()).find("img").attr("src");
}

这应该会很接近:
if (feed_image_type == "description") {
    var cdataText = $(this).firstChild.firstChild.textContent;
    var jqueryObj = $(cdataText);
    item_img = jqueryObj.find('img').attr('src');
}

3
你也可以尝试这个。
let str = `<description>
  <![CDATA[
   <img src="https://i.kinja-img.com/gawker-media/image/upload/s--E93LuLOd--/c_fit,fl_progressive,q_80,w_636/hd6cujrvf1d72sbxsbnr.jpg" /><p>With a surprise showing of skill and, at one point, a miracle, the bottom-ranked team in the European <em>League </em>Championship Series will not end the summer winless.<br></p><p><a href="http://compete.kotaku.com/european-league-team-finally-wins-its-first-series-of-t-1797363638">Read more...</a></p>
  ]]>
</description>`;

//We need to strip CDATA in our case. Otherwise the parser will not parse the contents inside it.
str = str.replace("<![CDATA[", "").replace("]]>", "")
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(str,"text/xml");
let images = [...xmlDoc.querySelectorAll('img')].map(image=>image.getAttribute('src'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接