【问题标题】:PhantomJS passing variable to page.openPhantomJS 将变量传递给 page.open
【发布时间】:2014-07-19 15:53:58
【问题描述】:

我需要在一个页面上捕获一个 URL,然后打开目标。什么是最优雅的解决方案?下面的代码不起作用,因为变量 url 基本上是本地的。

function() {
  page.open("https://www.google.com/blah");
},
function() {
  page.evaluate(function() {
    var url=document.getElementById('link42')[0]; //URL captured
  });
},
//opening the target 
function() {
  page.open(url);
},
function() {
  page.evaluate(function() {
    console.log(document.querySelectorAll('html')[0].outerHTML);
  });
} 

【问题讨论】:

    标签: variables url phantomjs argument-passing


    【解决方案1】:

    您可能可以将其设为全局。您只需要注意如何从页面上下文中获取 url。无法返回 DOM 元素,但您可以返回 JSON 可序列化的所有内容。

    引用page.evaluate:

    注意:评估函数的参数和返回值必须是简单的原始对象。经验法则:如果可以通过 JSON 序列化就可以了。

    var url;
    
    // function chainer
    function() {
      page.open("https://www.google.com/blah");
    },
    function() {
      url = page.evaluate(function() {
        return document.getElementById('link42').href; // href captured
      });
    },
    //opening the target 
    function() {
      page.open(url);
    }
    

    getElementById 只返回一个元素,所以不能使用[0]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 2013-02-11
      相关资源
      最近更新 更多