簡體   English   中英

從CasperJS start()讀取本地HTML文件

[英]Read a local HTML file from CasperJS start()

我正在編寫一個簡單的casperjs腳本來填充網站上相當復雜的表單。 網站的HTML代碼有點亂,我不想在每次測試腳本時都通過導航步驟來訪問頁面。

我將表單頁面保存為HTML文件,但我甚至無法將測試HTML文件正確加載到casperjs中。 這是代碼,文件和結果:

var casper = require('casper').create();

casper.start('file://test.html').then(function() {
    this.echo('started')
    this.echo(this.getPageContent())
});

casper.run(function(){
    this.echo('ended');
    casper.done();
});

測試文件:

<html>
    <head>
        <meta charset="utf-8">
        <title>My page</title>
    </head>
    <body>
        <h1 class="page-title">Hello</h1>
        <ul>
            <li>one</li>
            <li>two</li>
            <li>three</li>
        </ul>
       <footer><p>2012 myself</p></footer>
    </body>
</html>

執行結果:

C:>started
<html><head></head><body></body></html>
ended

為什么HTML正文中的標記消失了?

一切正常,絕對路徑:

var casper = require('casper').create();
casper.start('file:///home/root2/pjs/test.html').then(function() {
    this.echo('started')
    this.echo(this.getPageContent())
});

casper.run(function(){
    this.echo('ended');
    casper.done();
});

執行結果:

started
<html><head>
        <meta charset="utf-8">
        <title>My page</title>
    </head>
    <body>
        <h1 class="page-title">Hello</h1>
        <ul>
            <li>one</li>
            <li>two</li>
            <li>three</li>
        </ul>
       <footer><p>2012 myself</p></footer>


</body></html>
ended

您還可以嘗試指定這樣的絕對路徑:

file:///C://Full/Path/To/test.html

僅供參考,您可以使用這些函數獲取相對文件的絕對文件uri:

function getAbsoluteFilePath(relativePath) {
  return "file:///" + currentDir() + relativePath;
};

// Courtesy https://github.com/casperjs/casperjs/issues/141
function currentDir() {
  var sep = "/";
  var pathParts = fs.absolute(casper.test.currentTestFile).split(sep);
  pathParts.pop();

  return pathParts.join(sep) + sep;
}

要在您的方案中使用它,請使用以下命令:

// ...
casper.start(getAbsoluteFilePath('test.html')).then(function() {
    this.echo('started')
    this.echo(this.getPageContent())
});
// ...

您可以使用fs模塊獲取工作目錄的絕對路徑,然后連接協議“file://”和relativePath。

例如

const fs = require('fs');
var casper = require('casper').create();

// your casper logic here
console.log(getAbsoluteFilePath('test.html'));

casper.run();

function getAbsoluteFilePath(relativePath) {
  return "file://" + fs.workingDirectory + '/' + relativePath;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM