2014-11-14 2 views
0

RSS를 리팩터링하고 있으므로 CasperJS를 사용하여 몇 가지 테스트를 작성하기로했습니다.CasperJS에서 네임 스페이스가있는 태그를 선택하는 방법은 무엇입니까?

나는이 세 가지 코드를 시도했다 (") :"링크를 원자 ", 그러나 아무도는 RSS 코드는

test.assertExists("//atom:link", "atom:link tag exists."); 

test.assertExists({ 
    type: 'xpath', 
    path: "//atom:link" 
}, "atom:link element exists."); 

//even this... 
test.assertExists({ 
    type: 'xpath', 
    namespace: "xmlns:atom", 
    path: "//atom:link" 
}, "atom:link element exists."); 

작동하지 않습니다 다음 RSS의 요소의

하나는

<?xml version="1.0" encoding="utf-8" ?> 
<rss version="2.0" xml:base="http://example.org/" xmlns:atom="http://www.w3.org/2005/Atom" 
    xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/" 
    xmlns:content="http://purl.org/rss/1.0/modules/content/"> 
    <channel> 
     <title>RSS Title</title> 
     <description>RSS description</description> 
     <link>http://example.org</link> 
     <lastBuildDate>Mon, 10 Nov 2014 11:37:02 +0000</lastBuildDate> 
     <language>es-ES</language> 
     <atom:link rel="self" href="http://example.org/rss/feed.xml"/> 
     <item></item> 
     <item></item> 
    </channel> 
</rss> 

나는이 페이지의 데모에서 http://www.freeformatter.com/xpath-tester.html, foo : 가수는 다음에 의해 접근 가능하다는 것을 알았다 :

//foo:singers 

하지만 CasperJS에서는 이것이 작동하지 않는 것 같습니다 ...

누구나 네임 스페이스로 이러한 종류의 요소를 선택하는 방법을 알고 있습니까? CasperJS는 XPath에 의해 요소를 해결하기 위해 사용하는

답변

2

기능은 document.evaluate입니다 :

var xpathResult = document.evaluate(
xpathExpression, 
contextNode, 
namespaceResolver, 
resultType, 
result 
); 

당신이 source code으로 볼 때 namespaceResolver 항상 null입니다. 즉, CasperJS는 접두사가있는 XPath를 사용할 수 없습니다. 당신이 그것을하려고하면 당신은 user defined nsResolver을 가진 요소를 검색하는 자신 만의 방법을 만들어야 할 것입니다

[error] [remote] findAll(): invalid selector provided "xpath selector: //atom:link":Error: NAMESPACE_ERR: DOM Exception 14

얻을.

casper.myXpathExists = function(selector){ 
    return this.evaluate(function(selector){ 
     function nsResolver(prefix) { 
      var ns = { 
       'atom' : 'http://www.w3.org/2005/Atom' 
      }; 
      return ns[prefix] || null; 
     } 
     return !!document.evaluate(selector, 
       document, 
       nsResolver, 
       XPathResult.ANY_TYPE, 
       null).iterateNext(); // retrieve first element 
    }, selector); 
}; 
// and later 
test.assertTrue(casper.myXpathExists("//atom:link"), "atom:link tag exists."); 
+0

물론 문서에 포함 된 네임 스페이스를 구문 분석하여 수정할 수 있습니다. –

+0

정말 잘 작동합니다. 복사 붙여 넣기. 감사 Artjom. –

관련 문제