问题描述
我是Javascript和PhantomJS的新手,但我看起来很简单的目标已经证明比预期更难实现。我想编写一个加载网站的脚本,然后输出该页面上使用的Javascript变量的值。如果我在浏览器中打开该页面并打开Javascript控制台,我可以输入变量名称,它会告诉我与所述变量相关的值。我只是尝试使用PhantomJS重现此功能,以便我可以自动执行此任务。
I'm new to Javascript and PhantomJS, but my seemly simple objective has proven to be harder to achieve than expected. I want to write a script that would load a website, and then output the value of a Javascript variable used on that page. If I open that page in a browser and open the Javascript console, I can type in the variable name and it tells me the value associated to said variable. I just trying to reproduce this function but with PhantomJS so that I can automate this task.
有人能指出我正确的文档吗?假设PhantomJS是正确的方法,我无法找到如何做这样的事情。也许还有一个更简单的选择?
Could someone point me towards the right documentation for this? I haven't been able to find how to do such a thing, assuming PhantomJS is the right way to do this. Maybe there is a simpler alternative?
谢谢。
推荐答案
什么您需要了解的是,phantomJS具有两个 JavaScript环境,并且这两个环境彼此独立。内部文件是文档脚本(在任何浏览器中都有)。外面的一个是控制phantomJS应该做什么。它模拟用户。
What you need to understand is that phantomJS has two JavaScript environments and those two are independent of each other. The inner one is the document script (which you have in any browser). The outer one is controlling what phantomJS should do. It simulates the user.
所以在某种意义上你需要告诉phantomJS用户打开了JavaScript控制台任何类型 ......
。 执行此操作。
So in a sense you need to tell phantomJS "the user opened the JavaScript console any typed ...
". The evaluate command does this.
因此,要读取变量 foo
的值,请编写以下代码:
So to read the value of the variable foo
, you write this code:
var foo = page.evaluate(function() {
return document.foo;
});
注意:文件
并不严格必要但有助于保持两个环境在开发人员的头脑中分开。
Note: The document
isn't strictly necessary but it helps to keep the two environments apart in the head of the developer.
这篇关于使用PhantomJS从网站上读取javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!