PyV8,我能操作DOM结构吗?

2024-10-03 23:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有PyV8:

import PyV8
ctxt = PyV8.JSContext()

以及python的DOM结构,例如xml.dom

如何将.js文件馈送到PyV8,以便它可以更改现有的DOM结构。
如果我有它的内容:

^{pr2}$

我想删除dom项。在

PyV8有完美的hello world示例。但我想看看有用的东西。在

说清楚,我想做的是:
"Javascript file"-->;--魔法-->;--DOM, (already built with html file) and changed now with passed javascript file


Tags: 文件import内容hellowithjsxml结构
2条回答

这里有一个很好的例子来说明你想做什么:

https://github.com/buffer/thug

它是一个pythonhttp客户机,通过PyV8执行JS,用于安全研究,但是可以很容易地捆绑起来以满足更简单的需求。在

格式的方法。我尽我所能的间隔,但是我的屏幕阅读器不喜欢SO的格式控制。在

我想试着回答你的问题,尽管这个问题似乎有点模糊。请让我知道,如果我需要改写这个答案,以适应不同的情况。 我假设您正在尝试从web上获取一个HTML文件,并在该文件中运行Javascript,对该文档执行操作。 不幸的是,没有一个pythonxml库具有真正的DOM支持,而且我找到的每个包中都不存在w3cdom遵从性。 您可以使用pyv8w3c.pydom文件作为起始示例,并创建自己的完整dom。 W3C Sample Dom 不过,您需要重写这个模块,因为它不考虑引号或撇号。beauthoulsoup也不是最快的解析器。 我建议使用lxml.etree的目标解析器选项。 LXML Target Parser 搜索“feed解析器接口”。 然后,可以使用LXML加载HTML/Script文档,如下所示进行解析,并在创建的DOM上运行所需的每个脚本。在

找到下面的部分例子。(请注意,HTML标准是大量的、分散的,并且高度特定于浏览器,因此您的用法可能会有所不同)。在

class domParser(object):
    def __init__(self):
    #initialize dom object here, and obtain the root for the destination file object.
        self.dom = newAwesomeCompliantDom()
        self.document = self.dom.document
        self.this = self.document

    def comment(self, commentText):
    #add commentText to self.document or the above dom object you created
        self.this.appendChild(self.document.DOMImplementation.createComment(commentText))

    def start(self, tag, attrs):
    #same here
        self.this = self.this.appendChild(self.document.DOMImplimentation.newElement(tag,attrs))

    def data(self, dataText):
    #append data to the last accessed element, as a new Text child
        self.this.appendChild(self.document.DOMImpl.createDataNode(dataText))

    def end(self):
    #closing element, so move up the tree
        self.this = self.this.parentNode

    def close(self):
        return self.document

#unchecked, please validate yourself
x = lxml.etree.parse(target=domParser)
x.feed(htmlFile)
newDom = x.close()

相关问题 更多 >