【发布时间】:2014-10-21 21:08:59
【问题描述】:
我正在使用 Zombie.js 构建一个小型应用程序,但选项卡似乎无法正常工作。我当前的代码如下:
// libs used
var Zombie = require("zombie");
var assert = require("assert");
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
// server port and host configs
var server_port = 7777;
var server_ip_address = '127.0.0.1'
var app = express();
var httpServer = http.Server(app);
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use( bodyParser.urlencoded() ); // to support URL-encoded bodies
// o navegador
var browser = null,
result = "",
SITE_URL = 'http://en.wikipedia.org/wiki/Programming_language';
app.get('/', function (response, request) {
console.log('GET request received.');
console.log('Opening new tab: ' + SITE_URL);
// opens a tab
browser.open(SITE_URL);
// gets page content
result = browser.html('#content');
console.log('Tab open: '+browser.tabs.index);
console.log('Content: '+result);
request.send(result);
});
httpServer.listen(server_port, server_ip_address, function() {
console.log('Listening on ' + server_ip_address + ':' + server_port);
// creates the browser.
browser = new Zombie();
});
但是browser.html('#content'); 什么也没返回。在我看来,这些选项卡是打开的,但是当我尝试通过使用浏览器对象从当前打开的选项卡中提取数据时,它永远不会起作用。
我做对了吗?在 Zombie 2.0.8 中使用标签的“正确方法”是什么?我只是找不到任何信息/教程,而且官方文档对我来说不够清楚。
编辑:
正如 P.scheit 所指出的,open(url) 是不够的。这是主要的结果代码:
app.get('/', function (request, response) {
console.log('GET request received.');
if (request.query.url && request.query.selector) {
console.log('Opening new tab: ' + request.query.url);
browser.open(request.query.url);
browser.visit(request.query.url, function () {
result = browser.html(request.query.selector);
console.log('Loaded tab content. Sending back to user...');
response.send(result);
});
console.log('Tab open: '+browser.tabs.index);
} else if (request.query.tabid && request.query.selector) {
var tabid = request.query.tabid;
if (tabid < browser.tabs.length) {
browser.tabs.current = tabid;
console.log('Retrieving content of tab '+tabid+", sending back to user...");
result = browser.html(request.query.selector);
response.send(result);
} else {
console.log('Tab not found!');
response.send('Tab not found!');
}
} else {
console.log('Supply either [(the tab id) AND (search selector)] or [(the url to visit) AND (search selector)]!');
response.send('Supply either [(the tab id) AND (search selector)] or [(the url to visit) AND (search selector)]!');
}
});
运行服务器后,打开一些标签页:
$ curl "http://127.0.0.1:7777/?url=http://en.wikipedia.org/wiki/Programming_language&selector=h1"
$ curl "http://127.0.0.1:7777/?url=http://stackoverflow.com/users/3739186/cyberpunk&selector=h1"
$ curl "http://127.0.0.1:7777/?url=http://www.google.com.br&selector=a"
标签 0 中的数据:
$ curl "http://127.0.0.1:7777/?tabid=0&selector=a"
【问题讨论】:
-
你使用的是zombie 2.0还是旧的api?
-
很抱歉之前没有提到,但我使用的是新的 2.0.8 API
标签: javascript node.js zombie.js