【问题标题】:Open URL from file system using PhantomJS使用 PhantomJS 从文件系统打开 URL
【发布时间】:2014-06-24 11:05:21
【问题描述】:

page.open 我可以阅读有关如何使用http 打开页面的信息。

如何使用WebPage模块从文件系统中打开一个url?

我曾尝试省略http:// 并有一个带有../some_dir/foo.html 的网址,但似乎失败了。

我试过这个:

var page = require('webpage').create();
var fs = require('fs');

fs.changeWorkingDirectory('../foo/bar');

page.open('file://index.html', function(status)
{
    console.log(status);
    //console.log(document.title);
    phantom.exit();
});

输出“失败”。

我得到了测试绝对路径的建议,尝试这样做:

var page = require('webpage').create();
var fs = require('fs');

page.open('file:///absolute/path/to/index.html', function(status)
{
    console.log(page.title);
    console.log($('body').length);
    phantom.exit();
});

(无论是否调用 changeWorkingDirectory,但结果相同)

我得到一个页面标题,但 phantomjs 报告 $undefined,jQuery 包含在我的 html 文件中(太大,无法在此处发布)。它是这样包含的:

<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>

尝试运行函数也会产生类似的错误

找不到变量:function_name

【问题讨论】:

  • 你试过file://&lt;path&gt;吗?您可能需要绝对路径。
  • 尝试与 fs.changeWorkingDirectory 一起使用
  • 使用输出“失败”的测试更新问题。
  • 你试过绝对路径吗?
  • file://index.html 不是绝对路径吗?

标签: phantomjs


【解决方案1】:

您打开的页面/文件是否已经嵌入了 jquery?如果没有,您将需要在页面对象上使用 injectJs 或 includeJs,然后才能使用 $ 运算符。

http://phantomjs.org/page-automation.html

如果你只是做一个简单的 DOM 选择,我建议你直接调用

document.querySelector('body').length

因为这些功能已经存在于 Phantom 实例中。

【讨论】:

  • 是的,我有一个脚本标签,它是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 2018-01-06
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多