2014-11-21 79 views
1

我有一個RSS提要,並且需要從中爲我的測試提取最新的pubDate元素。做同樣的事情最好的方法是什麼?從RSS提要中提取XML元素值

RSS訂閱鏈接:https://secure.hyper-reach.com/rss/310085

示例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-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&amp;ver=0&amp;format=34&amp;nologin=1</link> 
      <guid isPermaLink="false">https://secure.hyper-reach.com/rss/item/257029</guid> 
     </item> 
     <item>...</item> 
     <item>...</item> 
</channel> 
</rss> 

我在做什麼:

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'); 
    }); 
}; 

我得到的錯誤是

uncaughtError: TypeError: 'undefined' is not an object (evaluating 'this._utils_.getElementByXPath')

回答

2

要檢索pubDate內容,您可以使用casper.fetchText功能,但它有一個缺點,它串接的所有文本節點爲一個字符串:

casper.echo(casper.fetchText("pubDate")); 

將打印

2014年11月21日星期五00:56:15 -0500Fri,2014年11月21日00:47:34 -0500Fri,2014年11月21日00:45:36 -0500

要實際檢索文本,您可以使用casper.getElementsInfo,它可以處理多個元素並提供text屬性。一個簡單的映射之後生成數組,你可以事後工作:

var pubDates = casper.getElementsInfo("pubDate").map(function(elementInfo){ 
    return elementInfo.text; // or even `return new Date(elementInfo.text)` 
}); 

但是因爲你只想要最新的一個和RSS排序最新到最舊的,你可以簡單地使用第一個(注意缺乏在getElementInfos):

var pubDate = casper.getElementInfo("pubDate").text; 

你以前的做法會工作,如果你想在頁面內容已經做到了這一點。 clientutils模塊只能在頁面上下文中訪問(在casper.evaluate之內)。

var pubDate = this.evaluate(function(){ 
    return __utils__.getElementByXPath('//pubDate').innerText; 
}); 

請注意__utils__兩側有兩個下劃線。您也無法將頁面上下文中的DOM元素傳遞給casper上下文,但是您可以傳遞字符串和其他基本對象。因此我返回了DOM元素的innerText屬性。該documentation這樣說:

注:參數和返回值的評估函數必須是一個簡單的原始對象。經驗法則:如果它可以通過JSON序列化,那麼它很好。