表单提交与casperjs – 新的url不加载

目标

在这里,我正在尝试在Pubmed网站上执行基本的search导航。 让我们说,我正在寻找的术语是Hello 。 我最后期望的是在点击searchbutton之后登陆一个结果页面。

问题

提交代码在Chrome浏览器的JavaScript控制台上完美工作。 但是它通过casperjs不起作用。 目前的url似乎保持不变。 我无法弄清楚问题在哪里。

我的代码

 // USAGE: casperjs test navigation_test.js var config = { url: 'https://www.ncbi.nlm.nih.gov/pubmed/', }; config.form = { "term": "Hello", }; casper.test.begin('Testing navigation and forms', 2, function suite(test) { test.comment('⌚ Loading ' + config.url + '...'); casper.start(config.url, function() { // adjust the view port this.viewport(1280, 1024); }); // #1 method-2 (short) casper.then(function() { this.fill('form#EntrezForm', config.form, true); }) // #2 casper.then(function() { test.assertUrlMatch(/term/, 'New location is ' + this.getCurrentUrl()); }); casper.run(function () { test.done(); }); }); 

额外的代码

上述代码中的#1 method很短。 我也尝试了更长的版本如下。 但它也没有工作。

 // #1 method-1 (long) casper.then(function() { this.evaluate(function() { $('term').value = "Hello" }); test.assertEvalEquals(function () { return $('term').value; }, "Hello", 'The search was filled out properly.'); this.click('button[id="search"][type="submit"][class="button_search nowrap"]'); // OR // this.clickLabel('Search', 'button'); // OR /*this.evaluate(function() { $('search').click(); // OR // document.getElementById('search').click(); });*/ }); 

在我提交一个表单或请求一个新的URI之后,我ALWAYS使用一个waitFor作为select器。 我有时会注意到,只是使用.then有时会失败。

这通过罚款(我也注意到你的url匹配是有点错误)

 var config = { url: 'https://www.ncbi.nlm.nih.gov/pubmed/', }; config.form = { "term": "Hello", }; casper.test.begin('Testing navigation and forms', 2, function suite(test) { casper.start(config.url, function () { this.viewport(1280, 1024); }); casper.then(function () { test.assertTitle("Home - PubMed - NCBI", "Title is Home - PubMed - NCBI"); this.fill('form#EntrezForm', config.form, true); }); //Changes made here! casper.waitForText("Search results", function () { test.assertUrlMatch(/pubmed\/\?term=Hello/, 'New location is ' + this.getCurrentUrl()); }); casper.run(function () { test.done(); }); }); 

在这里输入图像说明

更新尝试这个

添加一个失败的条件,并采取屏幕抓取看看发生了什么(或什么都没有发生)

 casper.waitForText("Search results", function () { test.assertUrlMatch(/pubmed\/\?term=Hello/, 'New location is ' + this.getCurrentUrl()); }, function() { casper.capture("grab.png"); }); 

您也可以在casper.test行的正下方添加一个用户代理string

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

也可以尝试增加超时,所以超过5秒,例如

  casper.waitForText("Search results", function () { test.assertUrlMatch(/pubmed\/\?term=Hello/, 'New location is ' + this.getCurrentUrl()); }, null, 10000); 

更新尝试这是很好的长期拍摄!

尝试用这个系数代替。 它应该填写表格并同时提交…

 casper.then(function () { test.assertTitle("Home - PubMed - NCBI", "Title is Home - PubMed - NCBI"); this.fillSelectors('form', { "input[id='term']": "Hello" }, true); });