Jef*_*yan 7 javascript jquery phantomjs
我只是习惯了PhantomJs,到目前为止它非常酷.
我正在尝试抓取网站并获取有关网站上产品的数据.每个产品页面都会加载产品的默认颜色.单击颜色样本时,它会通过运行函数来交换新颜色.每个可点击的颜色样本元素如下所示:
<input type="image" id="swatch_0" onclick="pPage.getColor(0);" src="http://www.site.com/img50067.jpg">
Run Code Online (Sandbox Code Playgroud)
getColor更新该颜色的缩略图和价格.每个可用颜色(swatch_0,swatch_1等)的id增量以及传递给getColor增量的参数.我想用PhantomJs迭代每种颜色并为每个颜色提取相关数据.
我已经加载了页面,加载了jQuery,并且可以为初始加载的颜色提取数据,但似乎没有任何东西可以让我执行点击事件.
这是我正在尝试的:
page.evalaute(function){
var selection = $('#confirmText').text(); // name of the color
var price = $('#priceText').text(); // price for that color
console.log('Price is: ' + price);
console.log('Selection is: ' + selection);
console.log($('#swatch_1'));
$('#swatch_1').trigger("click");
selection = $('#selectionConfirmText').text();
price = $('#priceText').text();
console.log('Price is: ' + price);
console.log('Selection is: ' + selection);
}
Run Code Online (Sandbox Code Playgroud)
这给了我:
console> Price is: $19.95
console> Selection is: blue
console> [Object Object]
console> TypeError: 'undefined' is not and object // repeating until I manually exit
Run Code Online (Sandbox Code Playgroud)
没有其他代码运行.我也试过没有像这样的jQuery触发事件:
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("swatch_1");
cb.dispatchEvent(evt);
Run Code Online (Sandbox Code Playgroud)
并直接运行该功能:
pPage.getColor(1);
Run Code Online (Sandbox Code Playgroud)
我得到相同的输出.任何帮助表示赞赏.
如果像onclick此处那样直接在 HTML 中指定处理程序,则可以直接使用 Javascript 调用它:
$(function() {\n $('#swatch_0')[0].onclick(); \n});\nRun Code Online (Sandbox Code Playgroud)\n\n\xe2\x80\x8b\n相信你也可以使用PhantomJS的page方法sendEvent()来发出原生点击事件。但看起来这有点复杂,因为您必须使用鼠标的 x,y 位置从 PhantomJS 上下文中调用它。未经测试的代码:
var elementOffset = page.evaluate(function() {\n return $('#swatch_1').offset(); \n});\npage.sendEvent('click', elementOffset.left + 1, elementOffset.top + 1);\nRun Code Online (Sandbox Code Playgroud)\n