我的 Xpath 适用于 $x 但不适用于 document.evaluate

问题描述 投票:0回答:1

我正在使用 AppleScript 来控制 Safari。现在我需要使用 AppleScript 的

do javascript
在 Safari 中执行 Javascript 来评估 Xpath 并使用 AppleScript

中的返回值

这个有效

$x('//div/div/a').map(link => link.href)

但是当我尝试这样的事情时

document.evaluate(('//div/div/a').map(link => link.href), document, null, 0, null)

我明白了

TypeError: ('//div/div/a').map is not a function. (In '('//div/div/a').map(link => link.href)', '('//div/div/a').map' is undefined)

根据 Google 的说法,此错误消息意味着我尝试在

map
上使用
non-array object
。我想我明白这意味着什么 - ('//div/div/a') 在执行
.map(link => link.href)
之前没有被评估但是我不知道如何表达这个声明以便可以应用
map
在数组上。

如果我这样加括号

(

document.evaluate(('//div/div/a')
)
.map(link => link.href), document, null, 0, null)

document.evaluate
没有得到足够的论据。我也试过了

(

document.evaluate(('//div/div/a'), document, null, 0, null))
)
.map(link => link.href)
认为
document.evaluate
会返回一个数组,但这让我得到了与上面相同的错误信息
map is not a function
.

我不确定

document.evaluate
甚至给出有意义的结果:

document.evaluate(('//div/div/a'), document, null, XPathResult.ANY_TYPE, null)

XPathResult {resultType: 4, invalidIteratorState: false, iterateNext: function, snapshotItem: function, ANY_TYPE: 0, …} = $3

这基本上不是一个空结果吗?也就是说,不是数组?

如何在 document.evaluate 或类似函数中使用 '//div/div/a').map(link => link.href 以便得到类似数组的数据结构作为结果?


更新:我发现这个 https://codereview.stackexchange.com/questions/167571/evaluating-an-xpath-with-document-evaluate-to-get-an-array-of-nodes 它适用于肤浅的水平-但后来我又回到了原来的problem-出于某种原因我无法使用xpath获取href-attribute-唯一的解决方案似乎是使用

.map(link => link.href)

javascript xpath applescript
1个回答
0
投票

在 XPathResult 上使用

iterateNext()
方法

arr = document.evaluate(('//div/div/a'), document, null, XPathResult.ANY_TYPE, null);
// XPathResult { resultType: 4, invalidIteratorState: false }

a = arr.iterateNext()
// <a class="s-avatar s-avatar__32 s-user-card--avatar" href="/users/2834978/lmc">

a.getAttribute("href")
// "/users/2834978/lmc"
© www.soinside.com 2019 - 2024. All rights reserved.