问题描述
我正在重构RSS,所以我决定用CasperJS编写一些测试。
I'm refactoring a RSS so I decided to write some tests with CasperJS.
RSS的元素之一是 atom:link()
One of the elements of the RSS is "atom:link" (")
我尝试了这三个代码,但均无效果
I tried this three codes, but none works
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>
我在此页面的演示中看到,foo:singers可以通过以下方式访问:
I saw that in a demo in this page http://www.freeformatter.com/xpath-tester.html, foo:singers is accesible by:
//foo:singers
但是在CasperJS中,这似乎行不通...
But in CasperJS seems that this don't work...
任何人都知道如何使用命名空间选择这种元素吗?
Anyone know how to select this kind of elements with a namespace?
推荐答案
CasperJS用于通过XPath解析元素的函数是:
The function which CasperJS uses to resolve elements by XPath is document.evaluate
:
var xpathResult = document.evaluate(
xpathExpression,
contextNode,
namespaceResolver,
resultType,
result
);
当您查看 namespaceResolver
始终为 null
。这意味着CasperJS不能使用带有前缀的XPath。如果尝试使用,则会得到
When you look into the source code the namespaceResolver
is always null
. That means that CasperJS cannot use XPaths with prefixes. If you try it, you get
您必须创建自己的方法来使用。
You would have to create your own method to retrieve elements with a user defined nsResolver.
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.");
这篇关于如何在CasperJS中选择带有名称空间的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!