Skip to content

Instantly share code, notes, and snippets.

@spirkaa
Created December 11, 2014 08:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save spirkaa/4c3b8ad8fd34324bd307 to your computer and use it in GitHub Desktop.
Save spirkaa/4c3b8ad8fd34324bd307 to your computer and use it in GitHub Desktop.
How to download captcha image with Python Selenium and Requests
img = driver.find_element_by_xpath("//div[@id='MailRuConfirm']/div/div[18]/form/div[1]/div[2]/div[2]/div[2]/img")
src = img.get_attribute('src')
img = requests.get(src)
with open('captcha.jpg', 'wb') as f:
f.write(img.content)
@haxshaan
Copy link

This isn't helping in my case. As I am facing a kind of dynamic url.
Everytime I get the element's src and save the content, I get a new image.

@THUzhangga
Copy link

This isn't helping in my case. As I am facing a kind of dynamic url.
Everytime I get the element's src and save the content, I get a new image.

Well, perhaps you can use selenium to save the screen, and then crop the image.

@ganeshkharad2
Copy link

ganeshkharad2 commented Jan 28, 2020

Below code will give you exact same image open in browser

`

Hit the url

    driver.get(link)

Paste captcha full xpath here

    ele_captcha = driver.find_element_by_xpath("/html/body/form/div[2]/div[3]/span/div[1]/div/span[3]/img")   

get the captcha as a base64 string

    img_captcha_base64 = 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'));
        """, ele_captcha)

save the captcha to a file

    with open(r"captcha.jpg", 'wb') as f:
        f.write(base64.b64decode(img_captcha_base64))
        `

for height and width -->. cnv.width = ele.width; cnv.height = ele.height; check your original captcha image size by downloading to local.Sometime original image size and the image tag size are different in those cases you get cropped or incomplete image

As Shown Below

import base64
img_base64 = driver.execute_script("""
    var ele = arguments[0];
    var cnv = document.createElement('canvas');
    cnv.width = 215; cnv.height = 80;
    cnv.getContext('2d').drawImage(ele, 0, 0);
    return cnv.toDataURL('image/jpeg').substring(22);    
    """, driver.find_element_by_xpath("/html/body/form/div[2]/div[3]/span/div[1]/div/span[3]/img"))   #"/html/body/form/div[2]/div[3]/span[3]/div[1]/img"))
with open(r"image.jpg", 'wb') as f:
    f.write(base64.b64decode(img_base64)) 

Copy link

ghost commented Feb 13, 2020

Hi Ganesh, thx for sharing your code!
I 've made some tests using your solution and the answer was a numeric response.
8098
My question here is how I use it to obtain the .jpg file.

import base64
ele_captcha = driver.find_element_by_xpath("//*[@id="imgCaptchaSerpro"]")
img_captcha_base64 = 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'));
""", ele_captcha)
with open(r"captcha.jpg", 'wb') as f:
f.write(base64.b64decode(img_captcha_base64))

@ganeshkharad2
Copy link

ganeshkharad2 commented Feb 13, 2020

Hi

Just copy your element full Xpath insted my Xpath

`
import base64

img_base64 = driver.execute_script("""
var ele = arguments[0];
var cnv = document.createElement('canvas');
cnv.width = this.width ; cnv.height = this.height;
cnv.getContext('2d').drawImage(ele, 0, 0);
return cnv.toDataURL('image/jpeg').substring(22);
""", driver.find_element_by_xpath("/html/body/form/div[2]/div[3]/span/div[1]/div/span[3]/img"))

with open(r"image.jpg", 'wb') as f:
f.write(base64.b64decode(img_base64))
`

thats it ! you will get the response image on the destination path
just copy and paste this code then put the full x path of your image ...try it ....and let me know

Copy link

ghost commented Feb 13, 2020

Ganesh,

I've tried your way and receive 0 as a response.
Your code created an "image.jpg" file but it seems to be broken. At least my image editor wasn't able to successfully open it.
I'm a little puzzled about what to expect from your solution.
Right now I'm working through dinamic captchas by takin screenshots.
Hope to heard from you soon.

CODE BELOW:
import base64

img_base64 = driver.execute_script("""
var ele = arguments[0];
var cnv = document.createElement('canvas');
cnv.width = this.width ; cnv.height = this.height;
cnv.getContext('2d').drawImage(ele, 0, 0);
return cnv.toDataURL('image/jpeg').substring(22);
""", driver.find_element_by_xpath("/html/body/p/table/tbody/tr/td/p/table/tbody/tr/td/form/font[2]/table[2]/tbody/tr/td[3]/font/img"))

with open(r"image.jpg", 'wb') as f:
f.write(base64.b64decode(img_base64))

@ganeshkharad2
Copy link

ganeshkharad2 commented Feb 13, 2020 via email

@teocns
Copy link

teocns commented Apr 8, 2020

I get script execution timeout instead, dunno what the issue is.
selenium.common.exceptions.TimeoutException: Message: script timeout
(Session info: chrome=80.0.3987.163)
The element looks fine and it's equal to the captcha element so the script itself might be the issue.,

@zvorgiygeonka
Copy link

I get script execution timeout instead, dunno what the issue is.
selenium.common.exceptions.TimeoutException: Message: script timeout
(Session info: chrome=80.0.3987.163)
The element looks fine and it's equal to the captcha element so the script itself might be the issue.,

+1

@ohidurbappy
Copy link

Below code will give you exact same image open in browser

`

Hit the url

    driver.get(link)

Paste captcha full xpath here

    ele_captcha = driver.find_element_by_xpath("/html/body/form/div[2]/div[3]/span/div[1]/div/span[3]/img")   

get the captcha as a base64 string

    img_captcha_base64 = 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'));
        """, ele_captcha)

save the captcha to a file

    with open(r"captcha.jpg", 'wb') as f:
        f.write(base64.b64decode(img_captcha_base64))
        `

for height and width -->. cnv.width = ele.width; cnv.height = ele.height; check your original captcha image size by downloading to local.Sometime original image size and the image tag size are different in those cases you get cropped or incomplete image

As Shown Below

import base64
img_base64 = driver.execute_script("""
    var ele = arguments[0];
    var cnv = document.createElement('canvas');
    cnv.width = 215; cnv.height = 80;
    cnv.getContext('2d').drawImage(ele, 0, 0);
    return cnv.toDataURL('image/jpeg').substring(22);    
    """, driver.find_element_by_xpath("/html/body/form/div[2]/div[3]/span/div[1]/div/span[3]/img"))   #"/html/body/form/div[2]/div[3]/span[3]/div[1]/img"))
with open(r"image.jpg", 'wb') as f:
    f.write(base64.b64decode(img_base64)) 

Works just fine.

@paulwababu
Copy link

Works fine! Saved my life there!

@tprogram9991
Copy link

I tried this but i get this error. Can you please tell me what can be the issue?

selenium.common.exceptions.JavascriptException: Message: javascript error: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment