获取所有表行并使用 CasperJS 中的 XPath 查询返回它们

Getting all table rows and returning them using an XPath query in CasperJS

本文关键字:XPath 中的 查询 返回 CasperJS 获取      更新时间:2023-09-26

我正在使用Casper.js来自动进行常规上传。我已经设法上传了文件并检查它是否有效,但我想解析如果出现错误则返回的表,但我得到错误[error] [remote] findAll(): invalid selector provided "[object Object]":Error: SYNTAX_ERR: DOM Exception 12.这是我代码的相关部分:

casper.then(function() {
    if (this.fetchText('.statusMessageContainer').match(/Sorry, the file did not pass validation. Please review the validation errors in the report below/)) {
        this.echo("Upload failed!", "ERROR");
        errors = this.evaluate(function() {
            var errorRows = __utils__.findAll({
                type: 'xpath',
                path: '//table[@id="uploadTable"]/tr[position()>1]'
            });
            return Array.prototype.forEach.call(errorRows, function(e) {
                return e;
            });
        });
        this.echo(JSON.stringify(errors));
    } else {
        this.echo("Upload successful", "INFO");
    }
});

有什么想法吗?

虽然你可能有一个XPath语法错误,但你必须知道你不能从传递给evaluate()方法的闭包中返回DOM元素;你必须将你的NodeListHTMLelement实例转换为一些原生的Javascript类型,例如。数组、对象、字符串等...

此外,ClientUtils 模块中还有一个方便的getElementsByXPath()方法,您可以从加载的每个页面中自动注入的__utils__实例中使用:

casper.then(function() {
    if (this.fetchText('.statusMessageContainer').match(/Sorry, the file did not pass validation. Please review the validation errors in the report below/)) {
        this.echo("Upload failed!", "ERROR");
        var errors = this.evaluate(function() {
            var errorRows = __utils__.getElementsByXPath('//table[@id="uploadTable"]/tr[position()>1]');
            return Array.prototype.map.call(errorRows, function(e) {
                return e.innerText; // let's get node text instead of HTMLelement!
            });
        });
        this.echo(JSON.stringify(errors));
    } else {
        this.echo("Upload successful", "INFO");
    }
});

您还可以使用 ClientUtils 书签在浏览器控制台中测试您的选择器。例如,单击书签并在 js 控制台中执行此操作:

__utils__.getElementsByXPath('//table[@id="uploadTable"]/tr[position()>1]')

然后你会看到你的选择器是否正确(它在我身边工作——我的意思是它在语法上是正确的)。

从您的错误来看,您的选择器似乎有问题。从我所看到的来看,它的设置正确,除了一件事:尝试将'//table[@id="uploadTable"]/tr[position()>1]'更改为'//table[@id='uploadTable']/tr[position()>1]'(将"更改为")

除此之外,您的 XPath 在语法上看起来是正确的,所以我不确定为什么它会成为无效的选择器。