edit: I manually adjusted cnv.width = this.width
to 120
and it seems to be working. Upon closer inspection, I discovered that the image has both a rendered size
and an intrinsic size
. The width is 35 for rendered size
and 40 for intrinsic size
, which may explain the issue.
I am attempting to retrieve a captcha image from a web page using selenium. Here is my approach based on examples found on this platform:
def get_ver_code(driver):
img = driver.find_element(By.XPATH, '//*[@id="imgCode"]')
img = driver.execute_async_script("""
var ele = arguments[0], callback = arguments[1];
ele.addEventListener('load', function fn(){
ele.removeEventListener('load', fn, false);
var cnv = document.createElement('canvas');
cnv.width = this.width; cnv.height = this.height;
cnv.getContext('2d').drawImage(this, 0, 0);
callback(cnv.toDataURL('image/jpeg').substring(22));
}, false);
ele.dispatchEvent(new Event('load'));
""", img)
with open(r"captcha.jpg", 'wb') as f:
f.write(base64.b64decode(img))
base64_decoded = base64.b64decode(img)
img = Image.open(io.BytesIO(base64_decoded))
img = np.array(img)
return img
This method works well overall, but I have noticed that the downloaded images are consistently cropped on the right side. While it doesn't usually impact the accuracy of the digits, occasionally it does. For instance, see this example: https://i.sstatic.net/zUK3S.jpg
Any suggestions on how to resolve this cropping issue?