如何获得<img>XML文件中的SRC值

How to get <img> src value from xml file?

本文关键字:SRC 文件 何获得 img XML      更新时间:2023-09-26

我正在尝试创建一个简单的rss提要网站。
我可以通过这样做获得一些rss提要:

let article = {
              'title': item.title,
              'image': item.image.url,
              'link': item.link,
              'description': item.description,
           }

大多数rss源的标题和链接工作,但图像和描述不。
由于许多rss收费在描述中使用图像作为html,例如:

{ title: 'The Rio Olympics Are Where TV Finally Sees the Future',
description: '<div class="rss_thumbnail"><img src="http://www.wired.com/wp-content/uploads/2016/08/GettyImages-587338962-660x435.jpg" alt="The Rio Olympics Are Where TV Finally Sees the Future" /></div>Time was, watching the Olympics just meant turning on your TV. That''s changed—and there''s no going back. The post <a href="http://www.wired.com/2016/08/rio-olympics-tv-finally-sees-future/">The Rio Olympics Are Where TV Finally Sees the Future</a> appeared first on <a href="http://www.wired.com">WIRED</a>.',...

我如何从它得到图像的url ?

编辑:

http.get("http://www.wired.com/feed/"...
  .on('readable', function()  {
        let stream = this;
        let item;
        while( item = stream.read()){
           let article = {
              'title': item.title,
              'image': item.image.url,
              'link': item.link,
              'description': item.description,
           }
           news.push(article);
        }
  })  

这是我的一些代码,基本上我试图从有线rss获取图像url。
如果我使用'image': item.image。Url,它不起作用。那么我应该把它改成什么呢?

使用xml2js将XML转换为json

var parseString = require('xml2js').parseString;
var xml = '<img title=''A San Bernardino County Fire Department firefighter watches a helitanker make a water drop on a wildfire, seen from Cajon Boulevard in Devore, Calif., Thursday, Aug. 18, 2016. (David Pardo/The Daily Press via AP)'' height=''259'' alt=''APTOPIX California Wildfires'' width=''460'' src=''http://i.cbc.ca/1.3730399.1471835992!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_460/aptopix-california-wildfires.jpg'' />';
parseString(xml, function (err, result) {
    console.log(JSON.stringify(result, null, 4));
    console.log(result["img"]["$"]["src"]);
});

使用正则表达式:

var res = description.match(/src=.*'.(jpg|jpeg|png|gif)/gi);

小提琴演示

一个想法是使用正则表达式。例:

var re = /(src=)('''htt.*''')/g
var img_string = "your image tag string"
var match = re.exec(img_string)
var result = match[1]

您可以使用DOMDocument解析器获取图像源。

$html = "<img title=''A San Bernardino County Fire Department firefighter watches a helitanker make a water drop on a wildfire, seen from Cajon Boulevard in Devore, Calif., Thursday, Aug. 18, 2016. (David Pardo/The Daily Press via AP)'' height=''259'' alt=''APTOPIX California Wildfires'' width=''460'' src=''http://i.cbc.ca/1.3730399.1471835992!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_460/aptopix-california-wildfires.jpg'' />";
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"