我正在测试将PhantomJS服务器与Python的Requests库一起使用的方法。
GET和POST请求按预期工作,我可以让PhantomJS服务器请求我想要的任何页面并将结果放到控制台,但我无法弄清楚如何使用{{1}发回页面内容}。请求对象没有response.write(page.content)
,text
或可用的content
内容。让raw
按预期工作的唯一方法是对响应内容进行硬编码。如果我将response.write()
添加到keep-alive
,则请求函数会挂起。
这是我的true
server.js
Python代码很简单:
var webserver = require('webserver').create();
page = require('webpage').create();
var service = webserver.listen(8080, function(request, response) {
if (request.method == 'POST') {
console.log(request.post);
var content = '';
page.open(request.post, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
response.statusCode = 200;
response.write('Page not responding.');
} else {
content = page.content;
response.statusCode = 200;
response.write(content);
}
})
} else {
response.statusCode = 200;
console.log(request.method == 'GET' );
response.write('No URL provided');
}
response.closeGracefully();
});
答案 0 :(得分:1)
发送数据后需要关闭连接:response.close();
另外我建议在POST请求中使用变量,因为response.post
实际上是一个对象。
var webserver = require('webserver').create();
page = require('webpage').create();
var service = webserver.listen(8080, function(request, response) {
if (request.method == 'POST') {
var url = request.post.url;
console.log(url);
var content = '';
page.open(url, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
response.statusCode = 200;
response.write('Page not responding.');
response.close();
} else {
content = page.content;
response.statusCode = 200;
response.write(content);
response.close();
}
})
} else {
response.statusCode = 200;
console.log(request.method == 'GET' );
response.write('No URL provided');
respone.close();
}
});
然后用url变量POST:
import requests
response = requests.post('http://127.0.0.1:8080, data = {'url':'http://python.org'})