javascript – PhantomJs点击链接或运行页面功能

我只是习惯了PhantomJs,到目前为止它非常酷.

我正在尝试抓取网站获取有关网站上产品的数据.每个产品页面加载产品的认颜色可见.单击颜色样本时,它会通过运行函数来交换新颜色.每个可单击的颜色样本元素如下所示:

<input type="image" id="swatch_0" onclick="pPage.getColor(0);" src="http://www.site.com/img50067.jpg">

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);

}

这给了我:

console> Price is: $19.95
console> Selection is: blue
console> [Object Object]
console> TypeError: 'undefined' is not and object  // repeating until I manually exit

没有其他代码运行.我也试过没有像这样的jQuery触发事件:

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click",true,window,false,null);
var cb = document.getElementById("swatch_1"); 
cb.dispatchEvent(evt);

并直接运行该功能

pPage.getColor(1);

我得到相同的输出.任何帮助表示赞赏.

解决方法

如果在此处直接在HTML中指定了onclick处理程序,则可以使用Javascript直接调用它:
$(function() {
    $('#swatch_0')[0].onclick(); 
});

我相信你也可以使用PhantomJS页面方法sendEvent()来发出本机点击事件.但看起来这有点复杂,因为你必须从PhantomJS上下文中用鼠标的x,y位置调用它.未经测试的代码

var elementOffset = page.evaluate(function() {
   return $('#swatch_1').offset(); 
});
page.sendEvent('click',elementOffset.left + 1,elementOffset.top + 1);

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...