Javascript 从RSS提要中提取XML元素值
我有一个RSS提要,我需要从中提取最新的pubDate元素用于测试。做同样的事情最好的方法是什么 RSS源链接: 示例XML:Javascript 从RSS提要中提取XML元素值,javascript,xml,xpath,rss,casperjs,Javascript,Xml,Xpath,Rss,Casperjs,我有一个RSS提要,我需要从中提取最新的pubDate元素用于测试。做同样的事情最好的方法是什么 RSS源链接: 示例XML: <?xml version="1.0" encoding="ISO-8859-1" ?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <atom:link href="https://secure.hyper
<?xml version="1.0" encoding="ISO-8859-1" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link href="https://secure.hyper-reach.com/rss/310085" rel="self" type="application/rss+xml" />
<link>https://secure.hyper-reach.com/rss/310085</link>
<title>Hyper-Reach Automated Test Account alerts feed "Automated RSS Test"</title>
<description>Constant feed of alerts from Automated Test Account via hyper-reach.com</description>
<lastBuildDate>Fri, 21 Nov 2014 00:56:15 -0500</lastBuildDate>
<language>null</language>
<ttl>5</ttl>
<item>
<title>Alert (2014-11-21)</title>
<pubDate>Fri, 21 Nov 2014 00:56:15 -0500</pubDate>
<description>This is a test message.</description>
<link>https://secure.hyper-reach.com/servlet/getprompt?prompt_id=122967&ver=0&format=34&nologin=1</link>
<guid isPermaLink="false">https://secure.hyper-reach.com/rss/item/257029</guid>
</item>
<item>...</item>
<item>...</item>
</channel>
</rss>
我得到的错误是
uncaughtError:TypeError:“undefined”不是对象(计算“this.\u utils.\uu.getElementByXPath”)
要检索
pubDate
内容,您可以使用该函数,但它有一个缺点,即它将所有文本节点连接到一个字符串中:
casper.echo(casper.fetchText(“pubDate”);
将打印
2014年11月21日星期五00:56:15-0500 2014年11月21日星期五00:47:34-0500 2014年11月21日星期五00:45:36-0500
要实际单独检索文本,可以使用它处理多个元素并提供text
属性。一个简单的映射之后会生成一个数组,您可以在以后处理该数组:
var pubDates=casper.getElementsInfo(“pubDate”).map(函数(elementInfo){
return elementInfo.text;//甚至`返回新日期(elementInfo.text)`
});
但是,由于您只需要最新的一个,并且RSS提要从最新到最旧排序,因此您可以简单地使用第一个(注意getElementInfo
中缺少s
):
var pubDate=casper.getElementInfo(“pubDate”).text;
如果您是在页面上下文中这样做的,那么前面的方法就会起作用。clientutils模块只能在页面上下文中访问(在casper.evaluate
中)
var pubDate=this.evaluate(函数(){
返回uuUtils.getElementByXPath('//pubDate').innerText;
});
请注意,\uuuuuutils\uuuuu
两侧有两个下划线。此外,不能将DOM元素从页面上下文传递到casper上下文,但可以传递字符串和其他基本对象。因此,我返回了DOM元素的innerText
属性。报告说:
注意:evaluate函数的参数和返回值必须是简单的原语对象。经验法则:如果可以通过JSON对其进行序列化,那么就可以了
checkRSSFeed = function() {
//first I navigate to a certain page in my website
var href = '';
casper.then(function() {
this.test.assertExists(x('//a[contains(@href, "SUBSTRING OF URL")]'), 'the element exists');
href = casper.getElementAttribute(x('//a[contains(@href, "SUBSTRING OF URL")]'), 'href');
}).then(function() {
this.open(href);
}).then(function() {
this.echo(this.getCurrentUrl());
var pubDate = '';
this.getPageContent();
pubDate = this._utils_.getElementByXPath('.//pubDate');
});
};