【问题标题】:How to select tags with namespaces in CasperJS?如何在 CasperJS 中选择带有命名空间的标签?
【发布时间】:2014-11-14 13:26:52
【问题描述】:

我正在重构一个 RSS,所以我决定用 CasperJS 编写一些测试。

RSS 的元素之一是 "atom:link" (")

我尝试了这三个代码,但没有一个有效

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:singers 可以通过以下方式访问:

//foo:singers

但在 CasperJS 中似乎这不起作用...

有人知道如何使用命名空间选择这种元素吗?

【问题讨论】:

    标签: javascript xml xpath rss casperjs


    【解决方案1】:

    CasperJS 通过 XPath 解析元素的函数是document.evaluate:

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

    当您查看 source code 时,namespaceResolver 始终是 null。这意味着 CasperJS 不能使用带有前缀的 XPath。如果你尝试它,你会得到

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

    您必须创建自己的方法来检索带有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.");
    

    【讨论】:

    • 您当然可以尝试通过解析文档中嵌入的命名空间来优化它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多