我是新手,试图使用xpath选择器获得有关casperJS的一些帮助。
我想从Google网站中选择XPath并确切地查找输入框,这里是HTML:
<input id="gbqfq" class="gbqfif" type="text" value="" autocomplete="off" name="q" style="border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; background: url("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D") repeat scroll 0% 0% transparent; position: absolute; z-index: 6; left: 0px; outline: medium none;" dir="ltr" spellcheck="false">
<div id="gs_sc0" class="gbqfif" style="background: none repeat scroll 0% 0% transparent; color: transparent; padding: 0px; position: absolute; z-index: 2; white-space: pre; visibility: hidden;"></div>
<input id="gs_taif0" class="gbqfif" disabled="" autocomplete="off" aria-hidden="true" style="border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; position: absolute; z-index: 1; background-color: transparent; color: silver; left: 0px;" dir="ltr">
<input id="gs_htif0" class="gbqfif" disabled="" autocomplete="off" aria-hidden="true" style="border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; position: absolute; z-index: 1; background-color: transparent; color: silver; transition: all 0.218s ease 0s; opacity: 0; left: 0px; text-align: left;" dir="ltr">
我的简单代码不起作用:
var casper = require('casper').create();
var x = require('casper').selectXPath;
casper.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36");
casper.start('www.google.com');
casper.wait(3000,function(){
this.echo(this.getTitle());
});
casper.then(function(){
casper.sendKeys(x('//*[@id="gbqfq"]'),"newegg.com" );
});
casper.then(function(){
casper.click(x('//*[@id="gbqfq"]'));
});
casper.run();
当我使用:casperjs search.js
结果最终是这样的:
E:\Projects\casperjs\mytestcase>casperjs search.js
CasperError: Cannot get informations from xpath selector: //*[@id="gbqfq"]: elem
ent not found.
E:/projects/casperjs/modules/casper.js:1058 in getElementInfo
E:/projects/casperjs/modules/casper.js:1589
E:/Projects/casperjs/mytestcase/search.js:21
E:/projects/casperjs/modules/casper.js:1553 in runStep
E:/projects/casperjs/modules/casper.js:399 in checkStep
我总是坚持从xpath获取元素,我使用的是casperJS v1.1.0-beta3和最新的phantomJS版本。
任何帮助将不胜感激!
答案 0 :(得分:1)
问题是您的网址,它不指向网络资源,而是指向本地文件。通过在加载网页后转储状态,您将很容易意识到:
casper.start('www.google.com', function() {
this.echo(this.status(true));
});
输出包含 - 除此之外 - 这一行(我从/tmp
执行了脚本):
"requestUrl": "file:///tmp/www.google.com",
要解决此问题,请添加http://
(如果您更喜欢加密,则添加https://
):
casper.start('http://www.google.com');