'Captcha image cropped on the left side

update: I manually changed cnv.width = this.width to 120 and it kind of works. I also found that the image has rendered size and intrinsic size. Width is 35 for rendered size and 40 for intrinsic size, so I guess this could be the reason.

I am trying to use selenium to get captcha image from a web page. Here is what I have tried based on examples from this site

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 is almost fine, except that the images downloaded are always slightly cropped on the right side. A lot of times it doesn't affect the digits, but sometimes it does. For example: enter image description here

How can I fix this?



Solution 1:[1]

Looks like it has something to do with the width & height of the elem. you putting the img into. Is there maybe some margin applied by some other css?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tyr