2016-12-04 30 views
-1

我使用selenium-webdriver和nodejs来报废页面。页面的一个元素是我想抓取图像的验证码。我一直在寻找,但我只找到java或python代码来做到这一点。Selenium webdriver nodejs - 如何裁剪图像

到目前为止我有:

function writeScreenshot(data, name) { 
    name = name || 'ss.png'; 
    var screenshotPath = '/Users/Projects/screenshots/'; 
    fs.writeFileSync(screenshotPath + name, data, 'base64'); 
}; 

driver.takeScreenshot().then(function(data) { 
    writeScreenshot(data, 'out1.png'); 
}); 

//location of captcha 
var capt = driver.findElement(webdriver.By.xpath('myXPath'); 
var location = capt.getLocation(); 
var captAltura = capt.getSize().getHeight(); 
var captLargura = capt.getSize().getWidth(); 

页面的截图工作。 “captcha的位置”设置的第二部分我不确定,因为我不知道如何继续。 我如何裁剪图像?

- 更新(HTML代码)

<form name="form" method="POST"> 
<table width="750" cellspacing="0" cellpadding="0" border="0"> 
    <tbody> 
    <tr bgcolor="#CCCCCC"> 
     <td width="100%" height="31" align="center"> 
     <font class="code">Code:</font> 
     <input type="text" name="captcha" size="4" maxlength="4" value="" title="Security Code" class="inputcaptcha" onclick="this.select()"> 
     <img src="captcha.php" width="90" align="middle"> 
     </td> 
    </tr> 
    </tbody> 
</table> 
</form> 
+0

可能需要将“myXPath”更改为验证码的xpath。 – Ouroborus

+0

@Ouroborus嗯,我刚刚编辑的问题。在代码中,xpath是正确的。一旦我得到了所有这些信息,我如何才能将整个网页截图裁剪为验证码? –

+0

你不能。你有两件事情正在进行。代码的第一部分是获取页面的屏幕截图。这与验证码相关并不特别有用。最后一部分试图在页面中实际找到验证码图片。为此,找到验证码图片的元素,提取图片的网址,分别检索图片。 – Ouroborus

回答

0

我结束了使用该库easyimage。参考:https://stackoverflow.com/a/32111192/3383534

首先你截取空洞页面,然后裁剪到你想要的元素。

我是这样做的:

function cropInFile (valorWidth, valorHeight, valorX, valorY, srcFile){ 
    easyimg.crop(
     { 
      src: pathFile, 
      dst: pathFile, 
      cropwidth: valorWidth, 
      cropheight: valorHeight, 
      x: valorX, 
      y: valorY, 
      gravity: 'North-West' 
     }, 
     function(err, stdout, stderr) { 
      if (err) throw err; 
     } 
    ); 
}; 

这些参数: valorWidth,valorHeight,valorX,valorY是你想要的元素。最后是第一个截图。