2016-12-04 32 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是你想要的元素。最後是第一個截圖。