-
-
Save spirkaa/4c3b8ad8fd34324bd307 to your computer and use it in GitHub Desktop.
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) |
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.
Works fine! Saved my life there!
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)'.
+1