【问题标题】:How do I read a .txt file with CasperJS and store info as variables for the script to use?如何使用 CasperJS 读取 .txt 文件并将信息存储为变量以供脚本使用?
【发布时间】:2015-10-09 17:36:02
【问题描述】:

大图是使用 Python 创建一个 .txt 文件,然后调用 CasperJS 脚本。一旦 CasperJS 脚本运行并保存了它的文件(在本例中为 .png),让 python 抓取该文件并移动到下一个任务。

如本问题所述,another stack overflow question。我主要关注的是 Artjom B. 提供的答案。他建议让 Python 保存一个包含我需要的变量的 .txt,在我的例子中是(日期,网址)示例,(2015 年 10 月 15 日,www.google.com)

我认为我的部分问题是我对 JSON 了解不多,但我认为我需要先制作两个脚本,然后再整合它们。

我的 Casper 脚本如下:

var casper = require('casper').create({
    pageSettings: {
        loadImages: true, // The WebPage instance used by Casper will
        loadPlugins: false // use these settings
    }
});

var utils = require('utils');
var x = require('casper').selectXPath;
var fs = require('fs');
var url = //url provided in txt file that casper reads;
var date = //date provided in text file

casper.start().viewport(1920, 1080);

casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X)');

casper.thenOpen(url); //using the variable which came from the text file

casper.wait(3000, function () {
    this.echo(this.getTitle());
    console.log("Got title, now rendering image.");
    this.capture('date.png'); //saving the file as the date, provided by the .txt file. 
    console.log("got image of home page :D")
});

casper.then(function () {
    casper.exit();
});

casper.run();

我认为这几乎可以概括。非常感谢您对此的任何指导,您知道的任何其他链接都可以帮助我以后在更大的 python 脚本中运行 Casper 脚本将非常有帮助。

TLDR:如何让 CasperJS 读取文本文件,将两个值(日期和 url)存储为变量,然后使用这些变量完成其工作?

【问题讨论】:

    标签: python json phantomjs casperjs


    【解决方案1】:

    JSON 与纯 JavaScript 对象非常相似。这是一个:

    {
        "url": "http://example.com/path",
        "date": "2015-10-15"
    }
    

    您可以像这样在 CasperJS (PhantomJS) 中直接要求 JSON:

    var config = require("config.json"); // file written from Python
    

    现在您可以在脚本中使用config.dateconfig.url。您不需要将这些属性分配给专用变量,但是您当然可以这样做以使变量更短:

    var url = config.url;
    var date = config.url;
    

    【讨论】:

    • 哦,嘿!我引用了你的另一篇文章:) 所以你写: var config = require("config.json"); // 从 Python 编写的文件 我是否将 // 从 Python 编写的文件替换为该文件的路径?即 C:\Users(my comp username)\PycharmProjects\pythontextfile.txt 还是我误解了?
    • 不,你用路径替换config.json。我不知道完整路径的行为如何。也许您想使用相对路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2013-10-19
    • 2016-11-26
    • 2022-09-23
    相关资源
    最近更新 更多