如何使用 casperjs 下载与我在浏览器中看到的页面相同的页面

How to use casperjs to download a page same as the one I see in the broswer

本文关键字:面相 浏览器 casperjs 何使用 下载      更新时间:2023-09-26

由于没有js或coffeescript,我打算使用casperjs下载页面并使用python来解析它。但是我发现我下载的页面不喜欢我在浏览器中看到的页面 - 实际上它们的某些部分在保存页面之前没有加载。我想原因可能是加载回调尚未执行。如果我想下载与我在浏览器中看到的页面相同的页面,我该怎么办?非常感谢!

我的代码(咖啡脚本):

urls =
  'jd' : 'http://list.jd.com/652-654-831-0-0-0-0-0-0-0-1-1-1-1-1-72-4137-33.html'
casper = require("casper").create()
process = (urls) ->
  casper.start "", ->
    @echo "begin to work"
  for name, url of urls
    casper.thenOpen url, ->
      @echo @download url, "#{name}.html"
process(urls)
casper.run()

您所见casper.download()实际下载文件。 由于您想要当前页面源,因此可以使用casper.getHTML() 。要将页面内容字符串实际写入文件,您可以使用 PhantomJS 提供的文件系统模块。它具有fs.write()功能。

把它们放在一起,它在 JavaScript 中看起来像这样:

var fs = require("fs");
casper.start();
for(name in urls){
    casper.thenOpen(name, function(){
        this.echo("download " + name);
        fs.write(name+".html", this.getHTML(), "w");
    });
}
casper.run();

或者在 CoffeeScript 中像这样:

casper = require("casper").create()
fs = require("fs")
casper.start "", ->
    @echo "begin to work"
for name, url of urls
    casper.thenOpen url, ->
        @echo "download " + name
        fs.write "#{name}.html", @getHTML(), "w"
casper.run()