[英]Accessing values of JS Global variables in HTML with PhantomJS
所以我有一段HTML看起来像这样:
<html>
<body>
<script>
var foo = {
bar: []
};
</script>
</body>
</html>
我正在尝试使用PhantomJS提取foo.bar的值。 我该怎么做? 到目前为止,我知道我的结构如下:
var webPage = require('webpage');
var page = webPage.create();
page.open(MY_URL, function(status) {
var foo = page.evaluate(function(){
//gets javascript from the HTML in the response
// and extracts foo from there
});
});
console.log(someVar);
phantom.exit();
似乎您应该可以使用
var foo = page.evaluate(function() {
return window.foo
})
console.log('foo =', foo)
这是您的做法,从幻影虚拟浏览器打开url,并从带有幻影的网页获取javascript返回值
const phantom = require('phantom');
openUrl = (req, res, next) => {
let url = 'your url goes here';
const {content, returnedFromPage} = await loadJsSite(url);
return res.json(returnedFromPage);
}
loadJsSite = async (url) => {
return new Promise( async (resolve, reject) => {
const instance = await phantom.create();
const page = await instance.createPage();
await page.on('onResourceRequested', function(requestData) {
console.info('Requesting', requestData.url);
});
const status = await page.open(url);
var returnedFromPage = await page.evaluate(function() {
return document.title;
});
const content = await page.property('content');
await instance.exit();
return resolve({content: content, returnedFromPage: returnedFromPage});
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.