gpt4 book ai didi

javascript - 在 casperjs 步骤中启用/禁用 javascript?

转载 作者:行者123 更新时间:2023-11-28 18:44:47 26 4
gpt4 key购买 nike

我正在使用 casper.open 加载带有一些发布数据的网址。

我需要解析 html 以从 html 中获取用户 ID,并在 html 评估之前插入使用该 ID 设置 window.name 的 js 代码。

在 url 加载后我无法执行此操作,因为如果未设置带 ID 的 window.name,它会被重定向到另一个 url(通过 js)。

casper.open('http://example.com', {
method: 'post',
data:{
'somefield': 'somevalue',
},
});

更新:

通过使用 casper.options.pageSettings.javascriptEnabled = false; 将其放置在 casper.start() 之前禁用 js,我成功在 js 重定向之前获取页面 html,但随后 js 在所有其他步骤中都保持禁用状态。

我可以在步骤中启用/禁用 js 吗?

这是我的代码:

casper.start().then(function () {

// some work

}).then(function () {

// Disable js
this.options.pageSettings.javascriptEnabled = false;

}).then(function () {

// POST call
casper.open('http://example.com', {
method: 'post',
data: {
'field': 'value'
}
});

}).then(function () {

// Enable js
this.options.pageSettings.javascriptEnabled = true;

}).then(function () {

var content = this.page.content;
var changedContent = content.replace("some text", "with text");

this.page.setContent(changedContent, this.getCurrentUrl());

});

来自 phantomjs 文档:

The settings apply only during the initial call to the page.open function. Subsequent modification of the settings object will not have any impact.

最佳答案

您可以 Hook 到表示 initialization of the page 的事件(包装 PhantomJS event ):

casper.on("page.initialized", function(){
this.evaluate(function(){
window.name = "whatever";
});
});

casper.start(url).run();
<小时/>

如果您确实需要访问该页面,则可以注册“page.resource.requested”事件并使用casper.open加载页面。通过此事件,您可以中止请求,例如重定向请求。由于重定向发生在同一个 URL 上,因此您必须找到一种不同的方法来区分对该 URL 的第一个请求和第二个请求。示例:

var firstUrlRequestDone = false;
var url = "some url";
casper.on("page.resource.requested", function(requestData, request) {
if (requestData.url.indexOf(url) === 0) {
if (!firstUrlRequestDone)
firstUrlRequestDone = true;
else
request.abort();
}
});
casper.start()
.thenOpen(url)
.thenEvaluate(function(){
// TODO: read DOM and change window.name
})
.thenOpen(url)
.run();
<小时/>

Or, can I disable page JavaScript in previous step and enable it in the next?

不,您需要启用 JavaScript 才能访问和更改 DOM。不过,您可以禁用 JavaScript、加载页面、更改它(通过替换)、重新启用 JavaScript 和 load the page from the changed string

示例:

casper.options.pageSettings.javascriptEnabled = false;
var changedContent, actualURL;
casper.start(url)
.then(function(){
var content = this.page.content;
changedContent = content.replace("something", "with something");
actualURL = this.getCurrentUrl();

this.page.settings.javascriptEnabled = true;
})
.thenOpen("http://example.com") // this is a dummy page to force re-evaluation of `page.settings`
.then(function(){
this.page.setContent(changedContent, actualURL);
})
.then(function(){
// TODO: do whatever you need
})
.run();

关于javascript - 在 casperjs 步骤中启用/禁用 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35556223/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com