gpt4 book ai didi

xml - 我如何使用 cxml-stp 的 find-recursively 和 find-recursively-if

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:45 25 4
gpt4 key购买 nike

我找不到示例,也无法弄清楚这些函数的文档:

假设我想找到第一个 <div class="summary">在 Stack Overflow 的首页上。我可以通过这种方式获取 HTML 树:

(defun get-page (url)
"Get STP(DOM alternative) representation of page"
(chtml:parse
(drakma:http-request url)
(cxml-stp:make-builder)))

(get-page "http://stackoverflow.com")

不过,从这里开始,我只是不知道是什么find-recursivelyfind-recursively-if应该看起来像真正的论点。

编辑:找到第一个的解决方案 <div class="summary">在 SO 的首页上使用 find-recursively-if :

(cxml-stp:find-recursively-if
(lambda (node)
(and (typep node 'cxml-stp:element)
(equal (stp:local-name node) "div")
(equal (stp:attribute-value node "class") "summary")))
(get-page "http://stackoverflow.com"))

最佳答案

这些函数遍历节点树并在找到所需节点(在 find-recursively 的情况下)或满足谓词的节点(在 find-recursively 的情况下)时返回-如果)。谓词可能应该对节点做一些事情,但可以是任意的。例如,这是返回第 10 个节点的方法(通过使用将在第 10 次调用时返回 true 的谓词):

;; return the 10th node
(let ((x 0))
(cxml-stp:find-recursively-if
(lambda (node)
(= (incf x) 10))
(get-page "http://stackoverflow.com")))

作为一个更现实的例子,这里是你如何检索一个具有本地名称 "title" 的元素(注意你只能在 上使用 local-name >elements,而不是任意的 node,所以 :key 函数有点笨拙):

CL-USER> (cxml-stp:find-recursively
"title"
(get-page "http://stackoverflow.com")
:key (lambda (node)
(if (typep node 'cxml-stp:element)
(cxml-stp:local-name node)
""))
:test 'string-equal)
;=>
;#.(CXML-STP:ELEMENT
; #| :PARENT of type ELEMENT |#
; :CHILDREN '(#.(CXML-STP:TEXT
; #| :PARENT of type ELEMENT |#
; :DATA "Stack Overflow"))
; :LOCAL-NAME "title"
; :NAMESPACE-URI "http://www.w3.org/1999/xhtml")

关于xml - 我如何使用 cxml-stp 的 find-recursively 和 find-recursively-if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20204610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com