Phantomjs无法打开浏览器打开的页面

时间:2016-09-07 11:09:19

标签: javascript jquery phantomjs

我有一个试图打开网址的Phantomjs脚本。 phantomjs返回此错误:

Unable to load resource (request ID:undefinedURL:http://foo.bar/tree/nav_value/27)
Error code: 203. Description: Error downloading http://foo.bar/tree/nav_value/27 - server replied: Not Found

但是当我使用Chrome浏览器打开网址http://foo.bar/tree/nav_value/27时,没有任何问题,页面已正确加载!

这是剧本:

// Read the Phantom webpage '#intro' element text using jQuery and "includeJs"

"use strict";
var page = require('webpage').create();
var system = require('system');

if (system.args.length != 2) {
    console.log("please pass 2 argument")
}
var company_id = system.args[1]
console.log("c", company_id)

page.onConsoleMessage = function(msg) {
    console.log("message", msg);
};

page.onResourceError = function(resourceError) {
    console.log('Unable to load resource (request ID:' + resourceError.id + 'URL:' + resourceError.url + ')');
    console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);

};

page.onError = function(msg, trace) {
    console.log("error", msg)
}

var nav_value;

page.open("http://foo.bar/tree/nav_value/27", 'post', 'username=navid&password=test', function(status) {
    if (status === "success") {
        page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
            page.evaluate(function() {
                nav_value = parseInt($("#value").text());
            });
            phantom.exit(0);
        });
    } else {
      phantom.exit(1);
    }
});

修改

奇怪的事发生了。当我在另一台机器上的Windows上使用phantomjs运行此代码时,它可以工作。但是在Ubuntu上它会返回错误!

phantomjs尝试打开的网址位于同一台服务器上。 (Ubuntu的)

有什么问题?

1 个答案:

答案 0 :(得分:1)

不确定这会有所帮助,但我有一些想法可以帮助我解决过去PhantomJS的问题。

首先,正如您所说,它适用于另一台计算机,您可能希望通过下载可执行文件并在Python脚本上指定路径来测试other versions of PhantomJS。版本1.9.8帮助我绕过了一些安全限制(我还留下了一些设置,以防它可能感兴趣)。

driver = webdriver.PhantomJS(
    executable_path='/path/to/the/downloaded/phantomjs19',
    # you can specify args, such as:
    service_args=[
        '--ignore-ssl-errors=true', 
        '--ssl-protocol=any', 
        '--web-security=false',
    ],
    # and also other capabilities:
    desired_capabilities={
        'phantomjs.page.settings.resourceTimeout': '5000',
        'phantomjs.page.settings.userAgent': (
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
            "(KHTML, like Gecko) Chrome/15.0.87"
        ),
    },
)

您也可以尝试查看升级Selenium是否有帮助。

pip install selenium --upgrade

可能有助于了解正在发生的事情的另一个想法是尝试在错误发生之前打印屏幕截图并记录页面源。你可以这样做:

# Set the window size to something appropriate for your tests.
driver.set_window_size(900, 800)
driver.save_screenshot('screen.png')

# Check if the page source matches your expectations.
with open('temp.html', 'w') as f:
    f.write(driver.page_source)

请告诉我这是否有帮助!